Automatically generate Jest mocks for your Javascript/Typescript files based on module usage.
Consider the following file:
const api = require('api');
const track = require('track');
const { flush } = require('cache');
function main(user) {
const userID = api.users.create(user);
track('create_user', userID);
flush(userID);
}
Running generate-jest-mocks
on it will result in the following manual Jest mocks being generated:
jest.mock('api', () => ({
users: {
create: jest.fn(),
}
});
jest.mock('track', () => jest.fn());
jest.mock('cache', () => ({ flush: jest.fn() }));
Or alternatively, when using --automock
, Jest automocks can be generated:
jest.mock('api');
jest.mock('track');
jest.mock('cache');
It also handles ES6 and Typescript files:
import cache, {set} from 'cache';
set('foo', 'bar');
cache.flush();
}
will output:
jest.mock('cache', () => ({
default: {
flush: jest.fn(),
},
set: jest.fn(),
}));
Install it using npm:
npm install -g generate-jest-mocks
generate-jest-mocks path/to/input.js
By default generate-jest-mocks
will output manual mocks. To generate automocks use --automock
or -a
.
By default a mock will be generated for each imported module. To specify specific modules to be mocked use --include=module
or -i=module
. Example:
generate-jest-mocks --include=api -i=cache path/to/input.js
To exclude one or more modules from being mocked use --exclude=module
or -e=module
. Example:
generate-jest-mocks --exclude=api -e=cache path/to/input.js
Import and call the default function:
const generate = require('generate-jest-mocks').default;
const output = generate(fs.readFileSync('path/to/file.js'), {
automock: false,
exclude: ['exclude/module'],
include: ['include/module'],
});
or with ES6 simply:
import generate from 'generate-jest-mocks';
- Fork the repository
- Create a new branch for your feature or bug fix
- Write your code
- Write tests that cover your code as much as possible
- Run all tests and ensure they pass
- Submit a pull request
Please try to keep your pull request small and focused. This will make it much easier to review and accept.