how to mock a library in jest
// lodash.js
const _ = require('lodash')
module.exports = () => _.repeat('abc', 3)
// lodash.test.js
jest.mock('lodash')
const lodashMock = require('lodash')
const { repeat } = jest.requireActual('lodash')
const lodashRepeat = require('../lodash')
describe('manual mock module', () => {
beforeEach(() => {
// setup mock
lodashMock.repeat.mockReturnValue(repeat('xxx', 3))
})
it('lodash repeat value', () => {
// expect lodashMock
expect(jest.isMockFunction(lodashMock)).toBeTruthy()
// expect lodash.js
expect(lodashRepeat()).toBeDefined()
expect(lodashRepeat()).toBe("xxxxxxxxx")
expect(lodashRepeat().length).toBe(9)
})
})
0
1
describe("mockImplementation", () => {
test("function", () => {
const mockFn1 = jest.fn().mockImplementation(() => 42);
const mockFn2 = jest.fn(() => 42);
expect(mockFn1()).toBe(42);
expect(mockFn2()).toBe(42);
});
Thank you!
1
0
4.25
8
import randomColor from "randomcolor";
jest.mock("randomColor", () => {
return {
randomColor: () => {
return mockColor('#123456');
}
}
});
let mockColor = jest.fn();
Thank you!
8
0
Are there any code examples left?
New code examples in category Javascript