The problem from the coverage report:
I have this code inside the components.ts
export class TimelinePlotComponent implements OnInit, OnChanges, OnDestroy {
form: FormGroup;
@Output() onchange: EventEmitter<any> = new EventEmitter<any>();
constructor() {}
initForm() {
this.form = new FormGroup({
timeRange: new FormControl(this.time_range_options_active, []),
metric: new FormControl(this.metric_options_active, []),
groupBy: new FormControl(this.group_by_options_active, []),
});
// How to unit test this part of the code
this.form.valueChanges.subscribe( res => {
console.log('form-changed');
this.onchange.emit(res);
});
}
}
fit('should listen for form changes', async() => {
component.form.controls['groupBy'].setValue('color');
fixture.detectChanges();
fixture.whenStable().then(() => {
// your expectations.
expect(component.form.valid).toBeTruthy();
component.onchange.subscribe( res => {
console.log('res: ', res);
});
});
});
error: nothing is happening, I dont know how to unit test a form that triggers an output event emitter.
As you can see this does not work, any help on how to unit test form changes?
Mock Service Dependency In Angular For unit testing the method, you need to mock the service method getPosts to test the component method. Let's start by writing unit test for testing method getPostDetails when the response from service method getPosts is an empty array. Add the following unit test case to the app.
To run the test, you will only need to run the command ng test . This command will also open Chrome and run the test in watch mode, which means your test will get automatically compiled whenever you save your file. In your Angular project, you create a component with the command ng generate component doctor .
Testing @Inputs To test inputs we need to do things: We need to be able to change the input property enabled on our component. We need to check that the button is enabled or disabled depending on the value of our input property.
I don't think you need the whenStable
at all, also the async
is not necessary. You should use detectChanges()
to trigger the change detection. But this should only be done before the actual start, to trigger the ngOnInit
hook (and friends).
Also use a spy
to make sure the Output has been called:
fit('should listen for form changes', () => {
spyOn(component.onchange, 'emit');
fixture.detectChanges();
component.form.controls['groupBy'].setValue('color');
expect(component.form.valid).toBeTruthy();
expect(component.onchange.emit).toHaveBeenCalled();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With