I have a component with a template like the following:
// Template
<form #f="ngForm" (ngSubmit)="onFormSubmit(f)">
<!-- A bunch of form fields -->
</form>
My component has a method like:
onFormSubmit(form: NgForm) {
this.save();
}
I want to write a test that basically looks like this, testing that the save function gets called when the form is submitted:
it('saves the widget when the form is submitted', () => {
let testForm = new NgForm([], []);
testForm.setValue({
name: "Hello",
category: "World"
});
component.onFormSubmit(testForm);
// Run tests to check that the component data was updated
expect(component.data.name).toEqual('Hello');
expect(component.data.category).toEqual('World');
});
How can I create a mock version of the form to pass in to the onFormSubmit()
function? I have tried doing the above and I get the error: "There are no form controls registered with this group yet. If you're using ngModel, you may want to check next tick (e.g. use setTimeout)."
Mocking is the act of creating something that looks like the dependency but is something we control in our test. There are a few methods we can use to create mocks.
First define a variable like this: let authService: AuthService; Then once the testbed has been set up, set this to the actual service being used by the TestBed inside the last beforeEach() : authService = TestBed.
There are no stubs in Jasmine, because there is no need to. The dynamic nature of JavaScript allows us to change the implementation of a JavaScript function on the fly. We can also stub functions using spies.
This should work
const testForm = <NgForm>{
value: {
name: "Hello",
category: "World"
}
};
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