Jest通过使用spyOn模拟嵌套函数,但仍然调用实际函数



getInfo调用同一文件中的getColor。我的意图是模拟getColor函数,我导入function .js作为模块和spyOngetColor。模拟的getColor应该返回"Red",但它仍然调用实际的函数并返回"Black"

函数文件

// func.js
function getColor() {
return "black"
}
function getInfo(){
const color = getColor()
const size = "L"
return `${color}-${size}`
}
module.exports = { getColor, getInfo }

测试文件

// 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");
});
});

我也试过requireActual,但它也调用实际的。

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")
})
})

如何在Jest中正确模拟嵌套函数?提前谢谢。

您正在监视func.getColor并嘲笑其实现,但getInfo正在调用局部作用域的getColor函数。你必须改变getColor被调用的方式来模拟它。

exports.getColor = function() {
return 'black'
}
exports.getInfo = function() {
const color = exports.getColor()
const size = 'L'
return `${color}-${size}`
}

Userewire模块来重写导出的属性。

您的测试文件看起来像这样:

const rewire = require('rewire')
describe('test', () => {
let func;
let getColorSpy;
beforeEach(() => {
getColorSpy = jest.fn()
func = rewire(__dirname + '/func.js') // import
func.__set__('getColor', getColorSpy) // rewrite content of getColor
})
test('should return Red-L when getColor returns Red', () => {
getColorSpy.mockReturnValue('Red')
const res = func.getInfo()
expect(res).toEqual("Red-L")
})
})

尽量避免像你的模块那样编写代码。

最新更新