npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@getbalance/automock-jest

v1.0.0

Published

[![ISC license](http://img.shields.io/badge/license-MIT-brightgreen.svg)](http://opensource.org/licenses/MIT) [![npm version](http://img.shields.io/npm/v/@automock/jest.svg?style=flat)](https://npmjs.org/package/automock "View this project on npm") [![Cod

Downloads

1

Readme

ISC license npm version Codecov Coverage ci

What is Automock?

Automock is a mocking library for unit testing TypeScript-based applications. Using TypeScript Reflection API (reflect-metadata) internally to produce mock objects, Automock streamlines test development by automatically mocking external dependencies.

Class constructor injection is commonly used within frameworks that implement the principles of dependency injection and inversion of control. Automock could be extremely useful with these frameworks and integrates easily with them.

Some well-known supported frameworks are: NestJS, Ts.ED, TypeDI and Angular.

Installation

npm i -D @automock/jest

Jest is the only test framework currently supported by Automock. Sinon will shortly be released.

Prerequisites

  • Automock can be used if the framework you're working with supports dependency injection (or you either implementing it manually by yourself).

  • The dependency injection engine makes use of class constructor injection.

Dependency injection is a style of object configuration in which an object's fields and collaborators are set by an external entity. In other words, objects are configured by an external entity. Dependency injection is an alternative to having the object configure itself.

🤔 Problem(s)

Consider the following class and interface:

interface Logger {
  log(msg: string, metadata: any): void;
  warn(msg: string, metadata: any): void;
  info(msg: string, metadata: any): void;
}

@Injectable() // Could be any decorator
class UsersService {
  constructor(private logger: Logger) {}
  
  generateUser(name: string, email: string): User {
    const userData: User = { name, email };
    this.logger.log('returning user data', { user: userData });
    return userData;
  }
}

An example of a unit test for this class may look something like this:

describe('Users Service Unit Spec', () => {
  let usersService: UsersService; // Unit under test
  let loggerMock: jest.Mocked<Logger>;
  
  beforeAll(() => {
    loggerMock = { log: jest.fn() }; // ! TSC will emit an error
    usersService = new UsersService(loggerMock);
  });
  
  test('call logger log with generated user data', () => {
    usersService.generateUser('Joe', '[email protected]');
    expect(loggerMock.log).toBeCalled(); // Verify the call
  });
});

One of the main challenging aspects of writing unit tests is the necessity to individually initialize all class dependencies and create a mock object for each of these dependencies.

Implementing the Logger interface is mandatory when working with the jest.Mocked (read more). In case the Logger interface is extended, TypeScript will enforce that the corresponding loggerMock variable also implement all of those methods, ending up with an object full of stubs

Another issue that arises when utilizing an IoC/DI in unit tests, is that the dependencies resolved from the container (DI container), are not mocked and instead yield actual instances of their classes. Therefor, running into the same issue, which is manually constructing mock objects and stub functions.

describe('Users Service Unit Spec', () => {
  let usersService: UsersService;
  let loggerMock: jest.Mocked<Logger>;
  let apiServiceMock: jest.Mocked<ApiService>;

  beforeAll(() => {
    loggerMock = { log: jest.fn(), warn: jest.fn(), info: jest.fn() };
    apiServiceMock = { getUsers: jest.fn(), deleteUser: jest.fn() };
    usersService = new UsersService(loggerMock, apiServiceMock);
  });

  test('...', () => { ... });
});

💡 Solution with Automock

import { TestBed } from '@automock/jest';

describe('Users Service Unit Spec', () => {
  let unitUnderTest: UsersService;
  let logger: jest.Mocked<Logger>;
  let apiService: jest.Mocked<UsersService>;

  beforeAll(() => {
    const { unit, unitRef } = TestBed.create(UsersService).compile();

    unitUnderTest = unit;
    apiService = unitRef.get(ApiService);
    logger = unitRef.get(Logger);
  });

  describe('when something happens', () => {
    test('then expect for something else to happen', async () => {
      await unitUnderTest.callSomeMethod();

      expect(logger.log).toHaveBeenCalled();
    });
  });
});

As seen in the preceding code sample, by using Automock, developers can focus more on testing the logic and less on the tedious task of manually constructing mock objects and stub functions. Furthermore, they don't need to worry about breaking the class type.

📜 License

Distributed under the MIT License. See LICENSE for more information.

📙 Acknowledgements

jest-mock-extended