angulartestingmockingng-mocks

MockComponent still includes the actual component


In my unit test I'm doing the following (via @ngneat/spectator):

    const createComponent = createComponentFactory({
        component: AppComponent,
        detectChanges: false,
        declarations: MockComponents(IgxToastComponent, NgxUiLoaderComponent),
        imports: [
            CommonModule, IgxToastModule, RouterTestingModule, NgxUiLoaderModule,
            MockComponent(HeaderComponent)
        ],
        mocks: [ToasterService]
    })

The HeaderComponent is a standalone component and so per the instructions on the ng-mock site I included it in the imports. When I run my tests though, I'm getting errors from the construction of the HeaderComponent since it include other services that this component doesn't use/mock. My understanding is that by using MockComponent it should have faked out the component so that even though the html still has <app-header> it doesn't actually try to load the HeaderComponent.

Am I supposed to be doing something differently?

I'm using ng-mocks 14.0.1


Solution

  • Because your components are standalone, you need to use MockBuilder. It will keep AppComponent as it is, whereas its imports will be mocked:

    // building TestingModule definition
    const dependencies = MockBuilder(
      [AppComponent, RouterTestingModule],
    ).build();
    
    const createComponent = createComponentFactory({
      component: AppComponent,
      detectChanges: false,
      mocks: [ToasterService],
    
      // adding dependencies where AppComponent is kept,
      // and its imports are mocks
      ...dependencies,
    });