Wondering what’s next for npm?Check out our public roadmap! »

    ng-mocks
    TypeScript icon, indicating that this package has built-in type declarations

    11.10.0 • Public • Published

    chat on gitter npm version build status coverage status language grade

    Mock components, services and more out of annoying dependencies in Angular tests

    ng-mocks helps to:

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

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

    • Angular 12 (Jasmine, Jest, Ivy, es5, es2015)
    • Angular 11 (Jasmine, Jest, Ivy, es5, es2015)
    • Angular 10 (Jasmine, Jest, Ivy, es5, es2015)
    • Angular 9 (Jasmine, Jest, Ivy, es5, es2015)
    • Angular 8 (Jasmine, Jest, es5, es2015)
    • Angular 7 (Jasmine, Jest, es5, es2015)
    • Angular 6 (Jasmine, Jest, es5, es2015)
    • Angular 5 (Jasmine, Jest, es5, es2015)

    Important links

    Very short introduction

    describe('app-component', () => {
      // We are going to test AppComponent.
      // Therefore, we want to mock its dependencies,
      // they are declared and imported in the module
      // where AppComponent has been declared too.
      // The next line says mock everything in AppModule,
      // but keep AppComponent as it is.
      beforeEach(() => {
        // The result of MockBuilder should be returned.
        return MockBuilder(AppComponent, AppModule);
      });
    
      // Stubbing observables in AuthService for all tests in the suite.
      beforeEach(() =>
        MockInstance(AuthService, () => ({
          isLoggedIn$: EMPTY,
          currentUser$: EMPTY,
        })),
      );
    
      it('should be created and initialized', () => {
        // Creating a spy on the 'check' method of the service.
        // MockInstance allows to spy / stub properties and methods
        // of declarations and providers before their instances
        // have been initialized.
        const spyCheck = MockInstance(
          AuthService,
          'check',
          jasmine.createSpyObj('AuthService.check'),
        ).and.returnValue(true);
    
        const fixture = MockRender(AppComponent);
        // Checking that the component has been created.
        expect(fixture.point.componentInstance).toBeDefined();
        // Checking that its ngOnInit method calls 'check' of the service.
        expect(spyCheck).toHaveBeenCalled();
      });
    });

    Profit.

    Extra

    Please support, if you like it:

    Thank you!

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

    Install

    npm i ng-mocks

    DownloadsWeekly Downloads

    110,234

    Version

    11.10.0

    License

    MIT

    Unpacked Size

    1.28 MB

    Total Files

    463

    Last publish

    Collaborators

    • avatar
    • avatar