我如何使用笑话测试以下代码段。我试图测试温斯顿自定义格式的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.
})
答案 0 :(得分:1)
如果需要测试的是b
,那么应该是间谍,而不是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');