所以我有一个 MatDialog 框,它在关闭时会发送一些表单值。然后我在 MatDialogRef 提供的 afterClosed 方法中分派一个动作。
当我手动测试它时,这工作得很好。但是在单元测试时,调度没有被调用,我的测试失败了。
我的代码在打开对话框时运行并在关闭时调度操作。
openAddUserDialog() {
this.addUserDialog = this.dialog.open(AddUserDialogComponent, {
width: 'max-content',
height: 'max-content',
minWidth: '35vw',
minHeight: '20vh',
autoFocus: false
});
this.addUserDialog.afterClosed().subscribe(result => {
console.log(result);
this.store.dispatch({type: UserActions.ActionTypes.TryAddUser, payload: result.value});
});
}
MatDialog 的模拟
export class MatDialogMock {
open() {
return {
afterClosed: () => of(initialValue)
};
}
}
测试床配置
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [MaterialModule, ReactiveFormsModule, BrowserAnimationsModule],
declarations: [ UserManagementDialogComponent ],
providers: [{provide: MatDialog, useClass: MatDialogMock}, provideMockStore({initialState})]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(UserManagementDialogComponent);
component = fixture.componentInstance;
store = TestBed.get(Store);
spyOn(store, 'dispatch').and.callThrough();
dialog = TestBed.get(MatDialog);
fixture.detectChanges();
});
以及应该通过的测试
it('should dispatch an action when the form is submitted', fakeAsync(() => {
spyOn(dialog, 'open').and.callThrough();
const dialogRef = dialog.open();
dialogRef.afterClosed().subscribe(result => {
console.log('verbrberbhyn', result);
expect(result).toEqual(initialValue);
tick();
expect(store.dispatch).toHaveBeenCalledTimes(1);
expect(store.dispatch).toHaveBeenCalledWith({
type: UserAtions.ActionTypes.TryAddUser,
payload: initialValue
});
});
}));