Search code examples
angulartestingkarma-jasminecustom-element

[SOLVED]How to test Angular custom elements and do coverage in module ngDoBootstrap


[Module Config](https://i.sstatic.net/rTgsU.png)

  • I would like to complete coverage in my module but can seem to find a way of referencing/spyOn the customElements.define inside the bootstrap.

bonus:

  • help with the useFactory coverage would be much appreciated.

  • this test pass so far.

  it('initializes', () => {
    const module: AppModule = TestBed.inject(AppModule);
    expect(module).toBeTruthy();
  });

  it('ngDoBootstrap', () => {
    const module: AppModule = TestBed.inject(AppModule);
    spyOn(module, "ngDoBootstrap");
    module.ngDoBootstrap();
    expect(module.ngDoBootstrap).toHaveBeenCalled();
  });

[RESOLVED] enter image description here


Solution

  • [RESOLVED]

    describe("AppModule", () => {
      let fixture: ComponentFixture<AppComponent>;
    
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          declarations: [
            AppComponent,
          ],
          imports: [
            HttpClientModule,
            AppModule,
            RouterTestingModule.withRoutes(APP_ROUTES),
          ],
          providers: [
            DynamicComponentService,
            RouterHelperService,
            Router,
            Injector,
          ],
          schemas: [CUSTOM_ELEMENTS_SCHEMA],
        }).compileComponents();
    
        fixture = TestBed.createComponent(AppComponent);
    
      });
    
    
      it("ngDoBootstrap", () => {
        const module: AppModule = TestBed.inject(AppModule);
    
        spyOn(module, "ngDoBootstrap").and.callFake(() => {
          const appModule = createCustomElement(AppComponent, {
            injector: TestBed.inject(Injector)
          })
    
          customElements.define("custom-element-name", appModule);
        }).and.callThrough();
        spyOn(customElements, "define");
    
        module.ngDoBootstrap();
        expect(module).toBeTruthy();
        expect(module.ngDoBootstrap).toHaveBeenCalled();
        expect(customElements.define).toHaveBeenCalled();
    
      })
    })