这里是一个非常简单的Angular组件,我想用Jest测试:
export class EmployeeComponent {
employees: Employee[] = [];
constructor(private dialog: MatDialog) {}
onOpenDialog(): void {
this.dialog.open(NewEmployeeDialogComponent)
.afterClosed()
.pipe(filter(employee => employee))
.subscribe(employee => this.employees.push(employee));
}
}
无论我尝试多少,都无法找到模拟open()和afterClosed()调用的优雅解决方案。除非,否则我将直接在上面的类中覆盖对话框值,这是糟糕的解决方案。 :(
describe('EmployeeComponent', () => {
let component: EmployeeComponent;
let fixture: ComponentFixture<EmployeeComponent>;
const mockMatDialog = { open: jest.fn() };
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [EmployeeComponent, NewEmployeeDialogComponent, EmployeeListComponent],
imports: [
BrowserAnimationsModule,
BrowserModule,
FormsModule,
HttpClientModule,
MatDialogModule,
MatListModule,
MatSelectModule
],
providers: [{ provide: MatDialog, useValue: mockMatDialog }],
}).overrideModule(BrowserDynamicTestingModule, {
set: {
entryComponents: [NewEmployeeDialogComponent]
}
});
});
beforeEach(() => {
fixture = TestBed.createComponent(EmployeeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should open the dialog and save a valid employee', () => {
component.dialog = TestBed.get(MatDialog);
spyOn(TestBed.get(MatDialog), 'open').and.returnValue({afterClosed: () => of(employee)});
component.openDialog();
expect(component.employees).toStrictEqual([employee]);
});
});
您对如何对其进行良好的测试有任何建议吗?