Jest Mock Module
Extends jest to allow deep auto mocking of a module by spying on all functions and properties.
Introduction
Getting Started
Install the extension using pnpm, npm, yarn etc.
npm install -D "jest-mock-module"
The Jest Object
The jest object needs to be extended in every test file. This allows access to the jest-mock-module
api.
jest.spy(moduleName)
This works like jest.doMock.
The main difference is a factory does not need to be provided as it automatically generates one using jest.createSpyFromModule
.
Internally uses jest.mock
so works with other jest
mocking methods.
jest.createSpyFromModule(moduleName)
This works like jest.createMockFromModule.
The main difference is the returned mock is created using jest.spyOnObject
.
jest.spyOnObject(object)
This creates a deep mock of the object spying on all the internal properties using jest-spy-on.
Example Usage
module.exports = {
testing: "123";
nested: {
test: () => true;
testing: "456";
}
}
import * as mock from "jest-mock-module";
mock.extend(jest);
jest.spy("src/example");
const example = require("src/example");
jest.isMockProp(example, "testing");
console.log(example.testing);
jest.spyOn(example).testing.mockValueOnce("789");
console.log(example.testing);
console.log(example.testing);
jest.isMockMethod(example.nested.test);
jest.isMockProp(example.nested, "testing");
It keeps the same structure of the module but replaces all functions and properties with jest mocks.
jest.createSpyFromModule
is exported and can be used like jest.createMockFromModule
. It is used internally by jest.spy
in combination with jest.mock
to provide a factory in place of Jest's automocking feature.
References