ng-mocks

用于模拟组件、指令、管道、服务和方便 TestBed 设置的 Angular 测试库。「Angular testing library for mocking components, directives, pipes, services and facilitating TestBed setup」

Github星跟蹤圖

chat on gitter
npm version
build status
coverage status
language grade

Mock components, services and more out of annoying dependencies for simplification of Angular testing

ng-mocks facilitates Angular testing and helps to:

  • mock Components, Directives, Pipes, Modules, Services and Tokens
  • reduce boilerplate in tests
  • access declarations via simple interface

The current version of the library has been tested and can be used with:

Angular ng-mocks Jasmine Jest Ivy
13 latest yes yes yes
12 latest yes yes yes
11 latest yes yes yes
10 latest yes yes yes
9 latest yes yes yes
8 latest yes yes
7 latest yes yes
6 latest yes yes
5 latest yes yes

Very short introduction

Global configuration for mocks in src/test.ts.
In case of jest, src/setupJest.ts should be used.

// All methods in mock declarations and providers
// will be automatically spied on their creation.
// https://ng-mocks.sudo.eu/extra/auto-spy
ngMocks.autoSpy('jasmine'); // or jest

// ngMocks.defaultMock helps to customize mocks
// globally. Therefore, we can avoid copy-pasting
// among tests.
// https://ng-mocks.sudo.eu/api/ngMocks/defaultMock
ngMocks.defaultMock(AuthService, () => ({
  isLoggedIn$: EMPTY,
  currentUser$: EMPTY,
}));

An example of a spec for a profile edit component.

// Let's imagine that there is a ProfileComponent
// and it has 3 text fields: email, firstName,
// lastName, and a user can edit them.
// In the following test suite, we would like to
// cover behavior of the component.
describe('profile', () => {
  // First of all, we would like to reuse the same
  // TestBed in every test.
  // ngMocks.faster suppresses reset of TestBed
  // after each test and allows to use TestBed,
  // MockBuilder and MockRender in beforeAll.
  // https://ng-mocks.sudo.eu/api/ngMocks/faster
  ngMocks.faster();

  // Let's declare TestBed in beforeAll
  // instead of beforeEach.
  // The code mocks everything in SharedModule
  // and provides a mock AuthService.
  beforeAll(() => {
    return TestBed.configureTestingModule({
      imports: [
        MockModule(SharedModule), // mock
        ReactiveFormsModule, // real
      ],
      declarations: [
        MockComponent(AvatarComponent), // mock
        ProfileComponent, // real
      ],
      providers: [
        MockProvider(AuthService), // mock
      ],
    }).compileComponents();
  });

  // A test to ensure that ProfileComponent
  // can be created.
  it('should be created', () => {
    // MockRender is an advanced version of
    // TestBed.createComponent.
    // It respects all lifecycle hooks,
    // onPush change detection, and creates a
    // wrapper component with a template like
    // <app-root ...allInputs></profile>
    // https://ng-mocks.sudo.eu/api/MockRender
    const fixture = MockRender(ProfileComponent);

    expect(
      fixture.point.componentInstance,
    ).toEqual(jasmine.any(ProfileComponent));
  });

  // A test to ensure that the component listens
  // on ctrl+s hotkey.
  it('saves on ctrl+s hot key', () => {
    // A fake profile.
    const profile = {
      email: 'test2@email.com',
      firstName: 'testFirst2',
      lastName: 'testLast2',
    };

    // A spy to track save calls.
    // MockInstance helps to configure mock
    // providers, declarations and modules
    // before their initialization and usage.
    // https://ng-mocks.sudo.eu/api/MockInstance
    const spySave = MockInstance(
      StorageService,
      'save',
      jasmine.createSpy('StorageService.save'),
    );

    // Renders <profile [profile]="params.profile">
    // </profile>.
    // https://ng-mocks.sudo.eu/api/MockRender
    const { point } = MockRender(
      ProfileComponent,
      { profile }, // bindings
    );

    // Let's change the value of the form control
    // for email addresses with a random value.
    // ngMocks.change finds a related control
    // value accessor and updates it properly.
    // https://ng-mocks.sudo.eu/api/ngMocks/change
    ngMocks.change(
      '[name=email]', // css selector
      'test3@em.ail', // an email address
    );

    // Let's ensure that nothing has been called.
    expect(spySave).not.toHaveBeenCalled();

    // Let's assume that there is a host listener
    // for a keyboard combination of ctrl+s,
    // and we want to trigger it.
    // ngMocks.trigger helps to emit events via
    // simple interface.
    // https://ng-mocks.sudo.eu/api/ngMocks/trigger
    ngMocks.trigger(point, 'keyup.control.s');

    // The spy should be called with the user
    // and the random email address.
    expect(spySave).toHaveBeenCalledWith({
      email: 'test3@em.ail',
      firstName: profile.firstName,
      lastName: profile.lastName,
    });
  });
});

Profit.

Extra

If you like ng-mocks, please support it:

Thank you!

P.S. Feel free to contact us if you need help.

主要指標

概覽
名稱與所有者help-me-mom/ng-mocks
主編程語言TypeScript
編程語言TypeScript (語言數: 4)
平台Docker, Linux, Mac, Windows
許可證MIT License
所有者活动
創建於2018-02-10 17:46:16
推送於2025-04-09 22:09:13
最后一次提交2025-04-10 00:09:11
發布數213
最新版本名稱v14.13.4 (發布於 )
第一版名稱v1.0.8 (發布於 2016-08-24 06:06:29)
用户参与
星數1.1k
關注者數10
派生數92
提交數20.9k
已啟用問題?
問題數421
打開的問題數54
拉請求數9968
打開的拉請求數24
關閉的拉請求數862
项目设置
已啟用Wiki?
已存檔?
是復刻?
已鎖定?
是鏡像?
是私有?