Angular 2 Component Testing Module with Other Component Dependencies

Basically, I have a component that looks like this:

export class CmpB extends CmpA {
    variableA:any = {};
    @Input() config:any = {};
    constructor(private serviceA: serviceA,
        @Optional() private CmpC?: CmpC) {
        super();
    }
    ngOnInit() {
        if (this.CmpC) {
            super.doSomething(parameterA);
            //other stuff
        }
    }
}

so basically I got CmpB that extends CmpA (which mutates the variable A depending on the configuration), and in order to do something, it needs a specific parent component of CmpC .... And I need to write a test for it, which actually checks for CmpA mutations.

my test is as follows

describe('CmpB', () => {
    let mock: any = MockComponent({ selector: "app-element", template: "<CmpC><CmpB></CmpB></CmpC>" });
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [mock, CmpC, CmpB],
            providers: [
                ServiceA
            ]
        }).compileComponents();
    });

    it('CmpB component test', async(() => {
        const appMock = TestBed.createComponent(mock);
        appMock.detectChanges();
        const el = appMock.debugElement.nativeElement as HTMLElement;
        expect(el.tagName).toEqual("DIV");
    }));
}

which works, and in terms of coverage, it goes through all this. But I need to manually set the configuration input and see how the variable changes the mutation; I can’t figure out how to do this.

Component

mock arises from the following code

    import { Component } from '@angular/core';

export function MockComponent(options: Component): Component {
  let metadata: Component = {
    selector: options.selector,
    template: options.template || '',
    inputs: options.inputs,
    outputs: options.outputs
  };

  class Mock {}

  return Component(metadata)(Mock);
}
+4

Source: https://habr.com/ru/post/1671270/


All Articles