/automock

Standalone Library for Automated Class Dependencies Mocking

Primary LanguageTypeScriptMIT LicenseMIT

ISC license npm version npm downloads Codecov Coverage ci


Logo

Automock

Standalone Library for Automated Class Dependencies Mocking

Write unit tests quickly and easily, with complete isolation of external class dependencies.

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.

Installation

npm i -D @automock/jest

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

🤔 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', 'joe@due.com');
    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.

💡 Demonstration / Example

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