Skip to content

Jest test utility with automatic mock creation for interfaces and classes

Notifications You must be signed in to change notification settings

Typescript-TDD/jest-ts-auto-mock

Repository files navigation

Jest Ts Auto Mock

Actions Status

This is a library that extend ts-auto-mock to be used with jest

The intention of the library is to automatically assign jest mock to functions giving you type safety

Requirements

typescript@^3.2.2
ts-jest@>=24 <27

Installation

  • A Transformer needs to be provided at compile time. We need to tell ts-jest to use ttypescript that allow us to use a transformer.

IMPORTANT:

  • set "cacheBetweenTests" as false

  • Add the transformer to your ts config

    {
      "compilerOptions": {
        ...
        "plugins": [
          { "transform": "ts-auto-mock/transformer", "cacheBetweenTests": false }
        ]
      }
    }
    • Enable ttypescript into the ts-jest configuration
       ...
       "globals": {
          "ts-jest": {
            "compiler": "ttypescript"
          }
        }
  • provide jest-ts-auto-mock config before your test

"jest": {
    ...
    "setupFiles": [
      "<rootDir>/config.ts"
    ]
   ...
  },
  • config file
import 'jest-ts-auto-mock'

Examples

ts-jest-ttypesctipt

Usage

  1. create an interface
interface Interface {
    methodToMock: () => string
}
  1. create a mock
const mock: Interface = createMock<Interface>();
  1. get the method mock

You can get the method spy in 2 different ways

Through method

import { On, method } from "ts-auto-mock/extension";
const mockMethod: Jest.Mock = On(mock).get(method(mock => mock.methodToMock));

Through string

import { On, method } from "ts-auto-mock/extension";
const mockMethod: Jest.Mock = On(mock).get(method('methodToMock'));
  1. trigger the method
someMethodThatWillTriggerInterfaceA();
expect(mockMethod).toHaveBeenCalled();

Authors

License

This project is licensed under the MIT License