我设置了一个 Jasmine spy 来测试当用户单击一个按钮(触发 goBack() 函数)时,它会打开一个对话框组件,或者就测试而言,调用一个东西。这是一个非常简单的测试,我有几乎相同的测试可以工作,但是这个因为某种原因没有。测试的输出说Expected spy open to have been called
。
带按钮的组件.component.ts
import { MatDialog } from '@angular/material/dialog';
export class ComponentWithAButton {
constructor(private closeDialog: MatDialog) {}
// A button triggers the following function
goBack(): void {
this.closeDialog.open(CloseDialogComponent);
}
}
带按钮的组件.component.spec.ts
import { MatDialog } from '@angular/material/dialog';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { ComponentWithAButton } from './component-with-a-button.component';
const closeDialogMock = { open: () => {} };
describe('ComponentWithAButton', () => {
let component: ComponentWithAButton;
let fixture: ComponentFixture<ComponentWithAButton>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ComponentWithAButton],
providers: [
{
provide: MatDialog,
useValue: closeDialogMock,
}
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(ComponentWithAButton);
component = fixture.componentInstance;
fixture.detectChanges();
});
describe('goBack', () => {
it('should call closeDialog.open', () => {
const closeDialogSpy = spyOn(closeDialogMock, 'open');
component.goBack();
expect(closeDialogSpy).toHaveBeenCalled();
});
});
});