测试使用开玩笑另一个函数内部的功能
我怎么可以用玩笑测试下面的代码片段。我想测试温斯顿自定义格式的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
需要进行测试,那么它应该是一个间谍,不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');