Angular Testing child component inputs

Testing child component inputs

When testing Angular components we sometimes run into the situation where we need to test a child components inputs in order for us to verify that the expected input parameters have been passed to the child component.

So in the example below, we want to verify that the child component param1 has been passed in the correct property.
<app-parent>

    <app-child [param1]="name"></app-child>

<app-parent>

How do we test this?

So we could create a test module, test component and register it with the TestBed but there's an easier way (I'll create a follow-up post on how to do this also).

Enter ngMocks

ngMocks is a library for testing Angular Component dependencies. More information can be found here on it https://github.com/ike18t/ng-mocks

How do we use it?

Firstly we need to import the library into our Jasmine test file.
import { MockComponent } from 'ng-mocks';
Then we need to configure the TestBed to mock our child component using ng-mocks MockComponent function.

beforeEach(() => {

        TestBed.configureTestingModule({
            declarations: [
                ParentComponent,
                MockComponent(ChildComponent), // create the mock
            ]
        }).compileComponents();
});

Finally, we create a unit test to verify that the child component got passed in the correct parameter input value.

describe('Test child inputs', () => {

    let fixture;
    let parentComponent;
    let childComponent;

    beforeEach(() => {
        fixture = TestBed.createComponent(ParentComponent);
        parentComponent = fixture.componentInstance;

        // set the name property on the parentComponent
        parentComponent.name = 'mark';
        childComponent = fixture.debugElement.query( // get the child component instance
          By.css('app-child')).componentInstance as ChildComponent;
        fixture.detectChanges();
    })

    it('should set param1 to the name parameter', () => {
        expect(childComponent.param1).toBe('mark');
    });
});

This is a really nice way to test that your child components input parameters are being set with the expected values instead of having to create mock components yourself or having to create E2E tests with Cypress or Protractor to test this logic.

Comments

Post a Comment

Popular posts from this blog

Grails 3.2: Bootstrap.groovy is not executed when run as an executable war/jar file