Careful about the NO_ERRORS_SCHEMA. Let's quote another part of the same the docs:

Shallow component tests with NO_ERRORS_SCHEMA greatly simplify unit testing of complex templates. However, the compiler no longer alerts you to mistakes such as misspelled or misused components and directives.

I find that drawback quite contrary to the purposes of writing a test. Even more so that it's not that hard to mock a basic component.

An approach not yet mentioned here is simply to declare them at config time:

@Component({
  selector: 'product-settings',
  template: '<p>Mock Product Settings Component</p>'
})
class MockProductSettingsComponent {}

@Component({
  selector: 'product-editor',
  template: '<p>Mock Product Editor Component</p>'
})
class MockProductEditorComponent {}

...  // third one

beforeEach(() => {
  TestBed.configureTestingModule({
      declarations: [
        ProductSelectedComponent,
        MockProductSettingsComponent,
        MockProductEditorComponent,
        // ... third one
      ],
      providers: [/* your providers */]
  });
  // ... carry on
});
Answer from Arnaud P on Stack Overflow
Top answer
1 of 4
119

Careful about the NO_ERRORS_SCHEMA. Let's quote another part of the same the docs:

Shallow component tests with NO_ERRORS_SCHEMA greatly simplify unit testing of complex templates. However, the compiler no longer alerts you to mistakes such as misspelled or misused components and directives.

I find that drawback quite contrary to the purposes of writing a test. Even more so that it's not that hard to mock a basic component.

An approach not yet mentioned here is simply to declare them at config time:

@Component({
  selector: 'product-settings',
  template: '<p>Mock Product Settings Component</p>'
})
class MockProductSettingsComponent {}

@Component({
  selector: 'product-editor',
  template: '<p>Mock Product Editor Component</p>'
})
class MockProductEditorComponent {}

...  // third one

beforeEach(() => {
  TestBed.configureTestingModule({
      declarations: [
        ProductSelectedComponent,
        MockProductSettingsComponent,
        MockProductEditorComponent,
        // ... third one
      ],
      providers: [/* your providers */]
  });
  // ... carry on
});
2 of 4
72

Found a nearly perfect solution, that will also correctly throw errors if someone refactors a component: https://www.npmjs.com/package/ng-mocks

npm install ng-mocks --save-dev

Now in your .spec.ts you can do

import { MockComponent } from 'ng-mocks';
import { ChildComponent } from './child.component.ts';
// ...
beforeEach(() => {
  TestBed.configureTestingModule({
    imports: [FormsModule, ReactiveFormsModule, RouterTestingModule],
    declarations: [
      ComponentUnderTest,
      MockComponent(ChildComponent), // <- here is the thing
      // ...
    ],
  });
});

This creates a new anonymous Component that has the same selector, @Input() and @Output() properties of the ChildComponent, but with no code attached.

Assume that your ChildComponent has a @Input() childValue: number, that is bound in your component under test, <app-child-component [childValue]="inputValue" />

Although it has been mocked, you can use By.directive(ChildComponent) in your tests, as well as By.css('app-child-component') like so

it('sets the right value on the child component', ()=> {
  component.inputValue=5;
  fixture.detectChanges();
  const element = fixture.debugElement.query(By.directive(ChildComponent));
  expect(element).toBeTruthy();

  const child: ChildComponent = element.componentInstance;
  expect(child.childValue).toBe(5);
});
🌐
Medium
medium.com › @e.kapprafael › mocking-child-components-in-angular-unit-tests-548fb0ccbdeb
Mocking Child Components in Angular Unit Tests | by Rafael Kapp | Medium
October 10, 2025 - import {Component, input, output, provideZonelessChangeDetection} from '@angular/core'; import {TestBed} from '@angular/core/testing'; import {App} from './app'; import {ChildComponent} from './child-component/child-component'; @Component({ selector: 'app-child-component', template: '', }) export class MockChildComponent { public readonly someInput = input<string>(); public readonly someOutput = output<void>(); } describe('App', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [App], }).overrideComponent(App, { add: {imports: [MockChildComponent]}, remove: {imports: [ChildComponent]} }) .compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(App); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); });
🌐
Sudo
ng-mocks.sudo.eu › mockcomponent
How to mock components in Angular tests | ng-mocks
March 15, 2026 - describe('Test', () => { let component: ...getComponent); component = fixture.componentInstance; }); }); To create a mock child component, simply pass its class into MockComponent:...
🌐
Atomic Spin
spin.atomicobject.com › mock-child-component-angular
How to Mock a Child Component When Writing Angular Tests
June 24, 2024 - Here’s a quick, to the point, explanation on how to mock child components.
🌐
Medium
medium.com › @abdul_74410 › towards-better-testing-in-angular-part-1-mocking-child-components-b51e1fd571da
Towards Better Testing In Angular. Part 1 — Mocking Child Components | by Abdul Rafehi | Medium
June 23, 2020 - Towards Better Testing In Angular. Part 1 — Mocking Child Components Tips and best practices on how to build better, more robust Angular applications I remember back to my first job out of …
🌐
GitHub
gist.github.com › lancevo › 83674ffa5ba386d5ef9a63a42ac7826e
Mock Child Component · GitHub
Mock Child Component · Raw · child.component.ts · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below.
🌐
Testing-angular
testing-angular.com › testing-components-with-children
Testing Components with children – Testing Angular
February 17, 2021 - How to write unit and integration tests for Components with children
🌐
TheCodeBuzz
thecodebuzz.com › home › angular unit testing and mocking components and child components
Angular Unit Testing and Mocking Components and Child Components | TheCodeBuzz
April 8, 2023 - Let’s write another test to check if deleteHero method of mockHeroService is called when we call the delete method of the HeroesComponent. Paste in the below code in heroes.component.spec.ts after the first test. import { HeroesComponent } from "./heroes.component"; import { ConstantPool } from "@angular/compiler"; import { of } from "rxjs"; describe('HeroesComponent', ()=>{ let component : HeroesComponent; let HEROES; let mockHeroService; beforeEach(()=>{ HEROES =[ {id:1, name:'IronMan', strength:8}, {id:2, name:'Batman', strength:8}, {id:3, name:'CaptainAmerica', strength:7}, {id:4, name:'
🌐
DEV Community
dev.to › fransaoco › testing-angular-components-with-children-using-jest-405f
Testing Angular Components with Children using Jest - DEV Community
April 21, 2025 - import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ParentComponent } from './parent.component'; import { Component, Input } from '@angular/core'; import { By } from '@angular/platform-browser'; // Child component mock @Component({ selector: 'app-child', template: '<div>{{ value }}</div>' }) class MockChildComponent { @Input() value: string = ''; } describe('ParentComponent', () => { let parentComponent: ParentComponent; let fixture: ComponentFixture<ParentComponent>; let childComponent: MockChildComponent; beforeEach(() => { TestBed.configureTestingModule({ declaration
Find elsewhere
🌐
Danielcornock
danielcornock.co.uk › articles › angular-testing-3-stubbing-child-components
Unit testing in Angular: Stubbing child components | Daniel Cornock
April 20, 2020 - Now, just after our first test, we can add another test to check that each product has been passed in to our child component. it('should display the products', () => { expect(getProducts()[0].componentInstance.product).toEqual({ product: 'product', number: '1' }); }); And there we have it! Now you should be able to run ng test, and get a nice green message telling you that both of your tests pass! Because of the way Angular runs its tests, it will run every spec file in your project when you run ng test.
🌐
O'Reilly
oreilly.com › library › view › mastering-angular-components › 9781788293532 › 23cadc6a-dd21-47fc-89ab-4096c42ba8a1.xhtml
Mocking child components - Mastering Angular Components - Second Edition [Book]
Mocking child components We've now looked at a very simple dummy component, and how to test it using the Angular TestBed, in conjunction with the inject and async helper functions.... - Selection from Mastering Angular Components - Second Edition [Book]
Top answer
1 of 3
2

For the nested component, we can mock them like this: https://angular.io/guide/testing-components-scenarios#stubbing-unneeded-components

In conclusion, your parent.component.spec.ts should be:

import { HttpClientTestingModule} from '@angular/common/http/testing';
import { Component } from '@angular/core';

describe('ParentComponent', () => {
  let component: ParentComponent;
  let fixture: ComponentFixture<ParentComponent>;
  let router: Router;


 @Component({selector: 'child', template: ''})
 class ChildStubComponent {}

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [ ParentComponent, ChildStubComponent ],
      imports: [
        AppRoutingModule, HttpClientTestingModule, BrowserAnimationsModule,
        RouterTestingModule.withRoutes(routes)
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA]
    })
      .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ParentComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router);
    spyOnProperty(router, 'url', 'get').and.returnValue('/somePath');
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});
2 of 3
0

The new Angular style especially for standalone components is documented here and it boils down to using overrideComponent:

    TestBed.configureTestingModule(
      Object.assign({}, appConfig, {
        providers: [provideRouter([]), UserService],
      }),
    ).overrideComponent(AppComponent, {
      set: {
        imports: [BannerStubComponent, RouterLink, RouterOutletStubComponent, WelcomeStubComponent],
      },
    });

Note this example use set (replacing all imports), but when you have other imports you do not want to have replaced, what your actual use case/requirement may be is to replace the component (with a stub). Funnily, the solution is actually simple if you understand it once: Just remove the old component and add a new - stubbed - one:

    await TestBed.configureTestingModule({
        imports: [
          // some unrelated, not to be modified imports
        ]
    }).overrideComponent(SystemUnderTestComponent, {
        remove: { imports: [ SomeComponent ] }, // removes old "original" component
        add: { imports: [ SomeStubComponent ] } // re-adds new component
      })
      .compileComponents();

same answer as here

🌐
YouTube
youtube.com › watch
24. Mocking the Child Component and add that Fake ...
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
Top answer
1 of 2
2

When you need a mock child component, consider usage of ng-mocks. It supports all Angular features including ViewChildren.

Then HelloComponent component will be replaced with its mock object and won't cause any side effects in the test. The best thing here is that there is no need in creating stub components.

There is a working example: https://codesandbox.io/s/wizardly-shape-8wi3i?file=/src/test.spec.ts&initialpath=%3Fspec%3DAppComponent

beforeEach(() => TestBed.configureTestingModule({
  declarations: [AppComponent, MockComponent(HelloComponent)],
}).compileComponents());

// better, because if HelloComponent has been removed from
// AppModule, the test will fail.
// beforeEach(() => MockBuilder(AppComponent, AppModule));

// Here we inject a spy into HelloComponent.answer 
beforeEach(() => MockInstance(HelloComponent, 'answer', jasmine.createSpy()));

// Usually MockRender should be called right in the test.
// It returns a fixture
beforeEach(() => MockRender(AppComponent));

it("should have 3 hello components", () => {
  // ngMocks.findAll is a short form for queries.
  const hellos = ngMocks.findAll(HelloComponent);
  expect(hellos.length).toBe(3);
});

it("should be able to access the 3 hello components as ViewChildren", () => {
  // the AppComponent
  const component = ngMocks.findInstance(AppComponent);

  // All its properties have been defined correctly
  expect(component.hellos).toBeDefined();
  expect(component.hellos.length).toBe(3);

  // ViewChildren works properly
  component.hellos.forEach(h => {
    expect(h).toEqual(jasmine.any(HelloComponent));
    expect(h.name).toBeDefined(); // WORKS
  });
});

it("should answer Bob", () => {
  const component = ngMocks.findInstance(AppComponent);
  const hellos = ngMocks.findAll(HelloComponent);
  const bob = hellos.find(h => h.componentInstance.name === "Bob");
  
  expect(bob.componentInstance.answer).not.toHaveBeenCalled();
  component.answer("Bob"); // WORKS
  expect(bob.componentInstance.answer).toHaveBeenCalled();
  });
2 of 2
0

I was able to get something to "work", but I don't like it.

Since the QueryList class has a reset() method that allows us to change the results, I can do this at the start of my test to change the results to point at the stub components that were created:

const hellos = fixture.debugElement.queryAll(By.css('hello'));
const components = hellos.map(h => h.componentInstance);
fixture.componentInstance.hellos.reset(components);

This "fixes" the tests, but I'm not sure how brittle it is. Presumably anything that subsequently does detectChanges will re-calculate the results of the QueryList and we'll be back to square one.

Here's a StackBlitz where I've put this code in the beforeEach method so that it applies to all the tests (which now pass).

🌐
Angular.love
angular.love › angular-unit-testing-viewchild
Angular Unit testing with @ViewChild
For unit testing we would really prefer to isolate our component from its children. Typically, we mock out our component’s dependencies by creating stubs for the child components.
Top answer
1 of 4
75

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:

<div id="task-list">
  <div *ngFor="let task of (tasks$ | async)">
    <app-task [task]="task" (click)="refresh()"></app-task>
  </div>
</div>

app-task is a sub component with the [task] input and the (click) output.

Ok great, now we want to write tests for my TaskListComponent and of course we don't want to test the real app-taskcomponent.

so as @Klas suggested we can configure our TestModule with:

schemas: [CUSTOM_ELEMENTS_SCHEMA]

We might not get any errors at either build or runtime, but we won't be able to test much other than the existence of the sub component.

So how can we mock sub components?

First we'll define a mock directive for our sub component (same selector):

@Directive({
  selector: 'app-task'
})
class MockTaskDirective {
  @Input('task')
  public task: ITask;
  @Output('click')
  public clickEmitter = new EventEmitter<void>();
}

Now we'll declare it in the testing module:

let fixture : ComponentFixture<TaskListComponent>;
let cmp : TaskListComponent;

beforeEach(() => {
  TestBed.configureTestingModule({
    declarations: [TaskListComponent, **MockTaskDirective**],
    // schemas: [CUSTOM_ELEMENTS_SCHEMA],
    providers: [
      {
        provide: TasksService,
        useClass: MockService
      }
    ]
  });

  fixture = TestBed.createComponent(TaskListComponent);
  **fixture.autoDetectChanges();**
  cmp = fixture.componentInstance;
});
  • Notice that because the generation of sub component of the fixture is happening asynchronously after its creation, we activate its autoDetectChanges feature.

In our tests, we can now query for the directive, access its DebugElement's injector, and get our mock directive instance through it:

import { By } from '@angular/platform-browser';    
const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
const mockTaskCmp = mockTaskEl.injector.get(MockTaskDirective) as MockTaskDirective;

[This part should usually be in the beforeEach section, for cleaner code.]

From here, the tests are a piece of cake :)

it('should contain task component', ()=> {
  // Arrange.
  const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));

  // Assert.
  expect(mockTaskEl).toBeTruthy();
});

it('should pass down task object', ()=>{
  // Arrange.
  const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
  const mockTaskCmp = mockTaskEl.injector.get(MockTaskDirective) as MockTaskDirective;

  // Assert.
  expect(mockTaskCmp.task).toBeTruthy();
  expect(mockTaskCmp.task.name).toBe('1');
});

it('should refresh when task is clicked', ()=> {
  // Arrange
  spyOn(cmp, 'refresh');
  const mockTaskEl = fixture.debugElement.query(By.directive(MockTaskDirective));
  const mockTaskCmp = mockTaskEl.injector.get(MockTaskDirective) as MockTaskDirective;

  // Act.
  mockTaskCmp.clickEmitter.emit();

  // Assert.
  expect(cmp.refresh).toHaveBeenCalled();
});
2 of 4
28

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', () => {
  beforeEach(() => {
    TestBed
      .configureTestingModule({
        declarations: [
          MyComponent
        ],
        schemas: [CUSTOM_ELEMENTS_SCHEMA]
      });
  });

  it(`should have as title 'app works!'`, async(() => {
    let fixture = TestBed.createComponent(MyComponent);
    let app = fixture.debugElement.componentInstance;
    expect(app.title).toEqual('Todo List');
  }));

});

This works in the released version of Angular 2.0. Full code sample here.

An alternative to CUSTOM_ELEMENTS_SCHEMA is NO_ERRORS_SCHEMA

🌐
Packtpub
subscription.packtpub.com › book › web-development › 9781838989439 › 10 › ch10lvl1sec87 › mocking-child-components-and-directives-using-the-ng-mocks-package
Mocking child components and directives using the ng- ...
Access over 7,500 Programming & Development eBooks and videos to advance your IT skills. Enjoy unlimited access to over 100 new titles every month on the latest technologies and trends
🌐
Blogger
mylifeandcode.blogspot.com › 2017 › 03 › how-to-mock-out-child-components-in.html
How To Mock Out Child Components In Unit Tests of Angular 2 Code
March 22, 2017 - I was struggling with this one for a bit but found a solution this past weekend. When writing unit tests of a component that contains child components, the solution is to do the following: 1. Create small mock classes in your test file to represent the child components and include just the functionality you’ll be mocking.