I ran into this same problem. I use jest
to test my Angular apps, not jasmine
, so I needed a slightly different solution, but by and large it mirrors Buczkowski's solution above:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Clipboard, ClipboardModule } from '@angular/cdk/clipboard';
import { FixedWidthTextBoxComponent } from './fixed-width-textbox.component';
describe('FixedWidthTextBoxComponent', () => {
let component: FixedWidthTextBoxComponent;
let fixture: ComponentFixture<FixedWidthTextBoxComponent>;
// I can get along without a spy here. I don't know what I would have
// done had I needed a spy, rather than a mock
const mockWriteText = jest.fn();
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [FixedWidthTextBoxComponent, ClipboardModule],
// I needed to pass an object here, rather than the mock function,
// because I'm using the "CdkCopyToClipboard" directive from Angular
// CDK to handle the copying to the clipboard
providers: [{ provide: Clipboard, useValue: { copy: mockWriteText } }],
}).compileComponents();
fixture = TestBed.createComponent(FixedWidthTextBoxComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('Copies data to the clipboard when the button is clicked', async () => {
component.contents = 'blah blah blah';
component.filename = 'testfile.txt';
component.label = 'Test Label';
fixture.detectChanges();
const buttons: HTMLButtonElement[] =
fixture.nativeElement.querySelectorAll('div button');
let copyButton!: HTMLButtonElement;
buttons.forEach((button) => {
if (button.textContent === 'Copy') {
copyButton = button;
}
});
copyButton.click();
expect(mockWriteText).toHaveBeenCalledWith(component.contents);
});
});
Clipboard
? – Calli