我正在使用https://testing-library.com/测试我的角度应用程序。
这是我的组件函数:
onCreateFormSubmit() {
if (this.createForm.valid && this.crud.isCreate) {
this.ssCreated.emit(created); //emits the data, needs to test
}
}
测试规范:
test('Testing add Subsystem operation', async () => {
const data = {
Id: 2,
Name: 'subsystem2',
IsDeletePossible: true,
CreatedBy: '',
CreatedDate: new Date(),
UpdatedBy: '',
UpdatedDate: new Date(),
UpdatedByName: 'test value',
CreatedByName: ''
} as ModelSubSystem;
const ssCreatedEmit = jest.fn();
const component = await render(SubSystemComponent, {
schemas: [CUSTOM_ELEMENTS_SCHEMA],
imports: [
HttpClientTestingModule,
FormsModule,
ReactiveFormsModule,
StoreModule.forRoot({}, { runtimeChecks: { strictStateImmutability: true, strictActionImmutability: true } }),
StoreModule.forFeature('pfservice', reducer),
EffectsModule.forRoot([]),
EffectsModule.forFeature([EffectsSubSystem])
],
componentProperties: {
onCreateFormSubmit: jest.fn(),
ssCreated: {
emit: ssCreatedEmit
} as any,
}
});
const componentInstance = component.fixture.componentInstance;
/*
* Testing the form by DOM.
*/
const createButton = component.getByTestId('btn-addRow');
component.click(createButton);
component.fixture.detectChanges();
// status changes because of click on button
expect(componentInstance.crud.isCreate).toBeTruthy();
component.fixture.detectChanges();
// onclick submit should not called, becasue of empty input
component.input(component.getByTestId('form-create-name-field-0'), {
target: {
value: data.Id
}
});
component.input(component.getByTestId('form-create-name-field-1'), {
target: {
value: data.Name
}
});
component.blur(component.getByTestId('form-create-name-field-1'));
component.input(component.getByTestId('form-create-name-field-2'), {
target: {
value: data.UpdatedByName
}
});
const submit = component.getAllByTestId('form-create-btn')[0];
component.click(submit);
component.fixture.detectChanges();
const name = componentInstance.createForm.controls['Name'];
const updatedByName = componentInstance.createForm.controls['UpdatedByName'];
expect(name.value).toEqual(data.Name);
expect(name.errors).toBeFalsy();
expect(updatedByName.value).toEqual(data.UpdatedByName);
expect(componentInstance.onCreateFormSubmit).toHaveBeenCalledTimes(1); //works.
expect(componentInstance.ssCreated).toHaveBeenCalledWith(data); // not works throw error
});
获取错误为:
Matcher error: received value must be a mock or spy function
如何用我设置的数据检查我的发射数据?
谢谢。
答案 0 :(得分:1)
我们正在spy
上使用emit
函数。
因此,您应该这样做:expect(componentInstance.ssCreated.emit).toHaveBeenCalledWith(data)