Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a fake NgForm object in an Angular unit test?

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)."

like image 527
Stewart Avatar asked Jul 26 '17 16:07

Stewart


People also ask

What is mock in Angular unit testing?

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.

How do you mock variable in Jasmine?

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.

How do you make a Jasmine stub?

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.


1 Answers

This should work

const testForm = <NgForm>{
    value: {
        name: "Hello",
        category: "World"
    }
};
like image 120
Aleksandr Petrovskij Avatar answered Oct 04 '22 02:10

Aleksandr Petrovskij