angular2 test, how do I mock sub component

Question!

How do I mock sub component in jasmine tests?

I have MyComponent, which uses MyNavbarComponent and MyToolbarComponent

import {Component} from 'angular2/core';
import {MyNavbarComponent} from './my-navbar.component';
import {MyToolbarComponent} from './my-toolbar.component';

@Component({
  selector: 'my-app',
  template: `
    <my-toolbar></my-toolbar>
    {{foo}}
    <my-navbar></my-navbar>
  `,
  directives: [MyNavbarComponent, MyToolbarComponent]
})
export class MyComponent {}

When I test this component, I do not want to load and test those two sub components; MyNavbarComponent, MyToolbarComponent, so I want to mock it.

I know how to mock with services using provide(MyService, useClass(...)), but I have no idea how to mock directives; components;

  beforeEach(() => {
    setBaseTestProviders(
      TEST_BROWSER_PLATFORM_PROVIDERS,
      TEST_BROWSER_APPLICATION_PROVIDERS
    );

    //TODO: want to mock unnecessary directives for this component test
    // which are MyNavbarComponent and MyToolbarComponent
  })

  it('should bind to {{foo}}', injectAsync([TestComponentBuilder], (tcb) => {
    return tcb.createAsync(MyComponent).then((fixture) => {
      let DOM = fixture.nativeElement;
      let myComponent = fixture.componentInstance;
      myComponent.foo = 'FOO';
      fixture.detectChanges();
      expect(DOM.innerHTML).toMatch('FOO');
    });
  });

Here is my plunker example;

http://plnkr.co/edit/q1l1y8?p=preview



Answers

If you use schemas: [CUSTOM_ELEMENTS_SCHEMA]in TestBed the component under test will not load sub components.

import { CUSTOM_ELEMENTS_SCHEMA } from [email protected]/core';
import { TestBed, async } from [email protected]/core/testing';
import { MyComponent } from './my.component';

describe('App', () =


As requested, I'm posting another answer about how to mock sub components with input/output:

So Lets start by saying we have TaskListComponent that displays tasks, and refreshes whenever one of them is clicked:

By : baryo


This video can help you solving your question :)
By: admin