angular2 test, how do I mock sub component


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';

  selector: 'my-app',
  template: `
  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(() => {

    //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; = 'FOO';

Here is my plunker example;


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

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { TestBed, async } from '@angular/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