jest mock module with jest.mock code example
Example 1: jest manual mock node module
const _ = require('lodash')
module.exports = () => _.repeat('abc', 3)
jest.mock('lodash')
const lodashMock = require('lodash')
const { repeat } = jest.requireActual('lodash')
const lodashRepeat = require('../lodash')
describe('manual mock module', () => {
beforeEach(() => {
lodashMock.repeat.mockReturnValue(repeat('xxx', 3))
})
it('lodash repeat value', () => {
expect(jest.isMockFunction(lodashMock)).toBeTruthy()
expect(lodashRepeat()).toBeDefined()
expect(lodashRepeat()).toBe("xxxxxxxxx")
expect(lodashRepeat().length).toBe(9)
})
})
Example 2: how to mock a library in jest
import randomColor from "randomcolor";
jest.mock("randomColor", () => {
return {
randomColor: () => {
return mockColor('#123456');
}
}
});
let mockColor = jest.fn();