getInfo
calls getColor
in the same file. My intention is to mock getColor
function, I import the func.js as a module and spyOn getColor
. The mocked getColor
is supposed to return "Red", but it still calls the actual function and returns "Black".
Function File
// func.js
function getColor() {
return "black"
}
function getInfo(){
const color = getColor()
const size = "L"
return `${color}-${size}`
}
module.exports = { getColor, getInfo }
Test File
// func.test.js
const func = require("./func")
describe("Coverage Change Test", () => {
beforeAll(() => {
const colorMock = jest.spyOn(func, "getColor"); // spy on otherFn
colorMock.mockImplementation(() => "Red");
});
afterAll(() => {
colorMock.resetAllMocks();
})
test("return Large Red", async () => {
const res = func.getInfo();
expect(res).toEqual("Red-L");
});
});
I also tried requireActual
, but it also calls the actual one.
const { getInfo, getColor } = require('./func');
jest.mock('./func', () => ({
...jest.requireActual('./func.'),
getColor: jest.fn().mockImplementation(() => 'Red'),
}))
describe('test', () => {
test('returns red', () => {
const res = getInfo()
expect(res).toEqual("Red-L")
})
})
How can I properly mock up a nested function in Jest? Thanks in advance.