我如何使用 jest 测试下面的代码片段。我正在尝试测试 winston 自定义格式 printf
// sample.js
import {aa:{b}} = require("thirparty-package")
const a = () => {
return b((log) => {
return `log message will be ${log.message}`
})
}
module.exports = {
a
}
// sample.test.js
const customFunctions = require('./sample')
test('should check b function is called and returns a string', () => {
expect(customFunctions.a).toHaveBeenCalled() // throwing error
//jest.fn() value must be a mock function or spy.
})
最佳答案
如果需要测试的是b
那么它应该是一个 spy ,而不是a
。
应该模拟第三方模块(demo):
const bMock = jest.fn();
jest.mock('thirparty-package', () => ({ aa: { b: bMock } }));
const { a } = require('./sample');
a();
const callback = bMock.mock.calls[0][0];
expect(callback).toEqual(expect.any(Function));
expect(callback({ message: 'foo' })).toBe('log message will be foo');
关于javascript - 使用 Jest 在另一个函数中测试一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54491134/