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
typescript@^3.2.2
ts-jest@>=24 <27
- 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.
-
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'
- create an interface
interface Interface {
methodToMock: () => string
}
- create a mock
const mock: Interface = createMock<Interface>();
- 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'));
- trigger the method
someMethodThatWillTriggerInterfaceA();
expect(mockMethod).toHaveBeenCalled();
This project is licensed under the MIT License