I am using https://testing-library.com/ for test my angular app.
Here is my component function:
onCreateFormSubmit() {
if (this.createForm.valid && this.crud.isCreate) {
this.ssCreated.emit(created); //emits the data, needs to test
}
}
test spec:
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
});
getting error as :
Matcher error: received value must be a mock or spy function
how to check my emit data with the data i sets?
Thanks in advance.
We're spy
ing on the emit
function.
Thus, you should do: expect(componentInstance.ssCreated.emit).toHaveBeenCalledWith(data)
For an example see https://github.com/testing-library/angular-testing-library/blob/master/src/app/examples/02-input-output.spec.ts