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
🌐
Angular
angular.dev › guide › testing › components-scenarios
Component testing scenarios • Angular
The stub is designed in such a way that any component or service that injects it will receive the stubbed implementation. It means that any call to getQuote receives an observable with a test quote. Unlike the real getQuote() method, this spy bypasses the server and returns a synchronous observable whose value is available immediately. To mock async functions like setTimeout or Promises, you can leverage Vitest fake timers to control whenever they fire.
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);
});
Discussions

unit testing - angular2 test, how do I mock sub component - Stack Overflow
This works in the released version of Angular 2.0. Full code sample here. An alternative to CUSTOM_ELEMENTS_SCHEMA is NO_ERRORS_SCHEMA ... what if the sub component has an input/output property and i want to create a mock for it to put spies on? More on stackoverflow.com
🌐 stackoverflow.com
Is Unit Testing in Angular overrated?
Testing can be frustrating to learn, but it is worth it. It can be difficult to see why it is worth it, but some key points: encourages better architecture ("bad" code is hard to test), protects against regressions, is a form of documentation, makes it easier to onboard other developers into the codebase, and in the end it will actually speed up development especially as a codebase grows as you are able to make changes with confidence and immediately see when things break. For your specific case, if you are creating a unit test for an addNotes() method then generally speaking you probably want to mock any dependencies you are dealing with - that will mean doing something like using jest.mock, or using useValue in your providers array in the TestBed set up, or supplying a mock component in the declarations, etc. If you are running into a lot of trouble mocking things, then it might also be a sign that the code might need to be refactored into simpler parts. More on reddit.com
🌐 r/Angular2
55
58
April 20, 2022
What's the latest consensus of writing unit tests and mocking standalone components?
You should write component unit tests, full stop. I personally think you should also invest in some form of code splitting, or change detection ($ nx affected test) to speed up your tests, especially if you are using something slow like MockComponent(). Would be interested in hearing others’ opinions. More on reddit.com
🌐 r/Angular2
4
5
May 11, 2023
What is the best way to test child components?
Consider using Spectator . It's a life saver. More on reddit.com
🌐 r/Angular2
4
4
September 22, 2020
🌐
Atomic Spin
spin.atomicobject.com › mock-child-component-angular
How to Mock a Child Component When Writing Angular Tests
June 24, 2024 - In effect, we’re replacing the component with one that is completely non-functional. We could give it some function if our test required that, of course, but in our example it isn’t necessary. Lastly, make sure you include the mock component class in the declarations when setting up the test bed:
🌐
Braydoncoyer
braydoncoyer.dev › blog › mocking-components-in-angular
Mocking Components in Angular
October 28, 2020 - What does this mean when we talk about unit testing in Angular? Whatever you're testing (whether that be a component, service, pipe, etc) should have all other dependencies (units) separated/mocked.
🌐
Sudo
ng-mocks.sudo.eu › get started
Mock components, services, and more to simplify Angular testing | ng-mocks
March 15, 2026 - ng-mocks is a testing library that helps with mocking services, components, directives, pipes and modules in tests for Angular applications.
🌐
Sudo
ng-mocks.sudo.eu › mockcomponent
How to mock components in Angular tests | ng-mocks
March 15, 2026 - To create a mock component, simply pass its class into MockComponent function.
🌐
DEV Community
dev.to › playfulprogramming-angular › how-do-i-test-and-mock-standalone-components-508e
How do I test and mock Standalone Components? - DEV Community
July 3, 2025 - MockedRequestInfoHolidayCard is a simple Component without any dependencies. What it has in common with the original is the selector. So when Angular sees the tag <app-request-info-holiday-card>, it uses the mocked version.
Find elsewhere
🌐
GitHub
github.com › ike18t › mock_component
GitHub - ike18t/mock_component: Easily mock components for Angular TestBed tests.
Mocked component with the same selector. ... import { async, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { MockComponent } from 'mock-component'; import { DependencyComponent } from './dependency.component'; import { TestedComponent } from './tested.component'; describe('TestedComponent', () => { let fixture: ComponentFixture<TestedComponent>; beforeEach(async() => { TestBed.configureTestingModule({ declarations: [ MockComponent(DependencyComponent) ] }) .compileComponents(); .then(() => { fixture = TestBed.createComponent(Exa
Starred by 4 users
Forked by 2 users
Languages   TypeScript 89.0% | JavaScript 11.0% | TypeScript 89.0% | JavaScript 11.0%
🌐
CodeCraft
codecraft.tv › courses › angular › unit-testing › mocks-and-spies
Testing with Mocks & Spies • Angular - Courses
We can create a fake AuthService called MockedAuthService which just returns whatever we want for our test. We can even remove the AuthService import if we want, there really is no dependency on anything else. The LoginComponent is tested in isolation: import {LoginComponent} from './login.component'; class MockAuthService { (1) authenticated = false; isAuthenticated() { return this.authenticated; } } describe('Component: Login', () => { let component: LoginComponent; let service: MockAuthService; beforeEach(() => { (2) service = new MockAuthService(); component = new LoginComponent(service);
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

🌐
Medium
medium.com › @redin.gaetan › angular-testing-dabc92a38b3f
Angular testing. How to mock natively standalone… | by Redin Gaetan | Medium
March 1, 2023 - Now, let’s do better with a mock. ... @Component({ selector: '[mat-button]', standalone: true, template: ` <ng-content></ng-content>`, }) class MatButtonMock {}
🌐
npm
npmjs.com › package › mock-component
mock-component - npm
Function creating a mock based on a passed in component for test. Latest version: 5.1.0, last published: 7 years ago. Start using mock-component in your project by running `npm i mock-component`. There are no other projects in the npm registry using mock-component.
      » npm install mock-component
    
Published   Apr 05, 2018
Version   5.1.0
Author   Isaac Datlof
🌐
npm
npmjs.com › package › ng-mocks
ng-mocks - npm
March 15, 2026 - An Angular testing library for creating mock services, components, directives, pipes and modules in unit tests. It provides shallow rendering, precise stubs to fake child dependencies. ng-mocks works with Angular 5 6 7 8 9 10 11 12 13 14 15 ...
      » npm install ng-mocks
    
Published   Mar 15, 2026
Version   14.15.2
🌐
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(); }); });
🌐
Testing-angular
testing-angular.com › testing-components-with-children
Testing Components with children – Testing Angular
February 17, 2021 - The MockComponent function expects the original Component and returns a fake that resembles the original.
🌐
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:'
🌐
Rainer Hahnekamp
rainerhahnekamp.com › home › how do i test and mock standalone components?
How do I test and mock Standalone Components? - Rainer Hahnekamp
March 4, 2024 - MockedRequestInfoHolidayCard is a simple Component without any dependencies. What it has in common with the original is the selector. So when Angular sees the tag <app-request-info-holiday-card>, it uses the mocked version.
🌐
GitHub
github.com › cnunciato › ng-mock-component
GitHub - cnunciato/ng-mock-component: An Angular module for mocking components.
Just specify the selector of the component you wish to mock (along with whatever other metadata properties you like), and MockComponent will supply that component with an empty template (unless you provide a template string, in which case, it'll use that instead). import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { MyComponent } from './src/my.component'; import { MockComponent } from 'ng2-mock-component'; describe('MyComponent', () => { let fixture, element; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ MyComponent, MockComponent({ selector: 'my-subcomponent' }) ] }); fixture = TestBed.createComponent(MyComponent); element = fixture.debugElement; }); it('works', () => { fixture.detectChanges(); expect(element.query(By.css('my-subcomponent'))).not.toBeNull(); }); });
Starred by 53 users
Forked by 12 users
Languages   TypeScript 100.0% | TypeScript 100.0%
🌐
Christianlydemann
christianlydemann.com › all-you-need-to-know-about-mocking-in-angular-tests
All You Need to Know About Mocking in Angular Tests (2020) – Christian Lüdemann
February 9, 2020 - The examples are based on my Angular TODO app with best practices repository. For mocking component, the easiest solution I have found is to avoid needing to mock components by shallow testing, that is, use schemas: [NO_ERRORS_SCHEMA] so the component under test’s template is not instantiating component tags.
🌐
npm
npmjs.com › package › ng2-mock-component
ng2-mock-component - npm
Just specify the selector of the component you wish to mock (along with whatever other metadata properties you like), and MockComponent will supply that component with an empty template (unless you provide a template string, in which case, it'll use that instead). import { TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { MyComponent } from './src/my.component'; import { MockComponent } from 'ng2-mock-component'; describe('MyComponent', () => { let fixture, element; beforeEach(() => { TestBed.configureTestingModule({ declarations: [ MyComponent, MockComponent({ selector: 'my-subcomponent' }) ] }); fixture = TestBed.createComponent(MyComponent); element = fixture.debugElement; }); it('works', () => { fixture.detectChanges(); expect(element.query(By.css('my-subcomponent'))).not.toBeNull(); }); });
      » npm install ng2-mock-component
    
Published   Aug 15, 2019
Version   0.2.0
Author   Christian Nunciato