Mock Components

Last updated last month

Sometimes it's helpful to pass a mock implementation of other components.

import { MockComponent, createHostComponentFactory } from '@netbasal/spectator';
const createHost = createHostComponentFactory({
component: SettingsPanelComponent,
declarations: [
MockComponent({ selector: 'da-widget-group-selection' }),
MockComponent({ selector: 'da-widget-settings', inputs: ['widget', 'type'] })

You can create a basic mock component by calling the MockComponent function, passing in the same parameters you would find in regular @Component({...}) metadata.

This allows you to ensure that the template of the component under test will still compile, even if the test module is missing the imports or declarations required to create some of its child components.

If you pass the original, unmocked class to MockComponent using the identifier option, you will later be able to retrieve the instance of the mocked component:

import { MockComponent, createTestComponentFactory } from '@netbasal/spectator';
import { UnderTestComponent } from './under-test.component';
import { ExampleComponent } from '../example/example.component';
// UnderTestComponent instantiates ExampleComponent in its template
const createComponent = createTestComponentFactory({
component: UnderTestComponent,
declarations: [
MockComponent({ selector: 'example-component', identifier: ExampleComponent })
// ... after instantiating a spectator instance ...
const exampleComponentInstance = spectator.query(ExampleComponent);