请允许我指出,可以找到与此类似的问题here https://stackoverflow.com/questions/46158728/how-to-mock-third-party-modules-with-jest,但接受的答案的解决方案对我不起作用。还有另一个同样的问题,其答案建议直接操作函数的原型,但这同样没有成果。
我正在尝试使用 Jest 来嘲笑this https://www.npmjs.com/package/sharpNPM模块,堪称“犀利”。它需要一个图像缓冲区并对其执行图像处理/操作操作。
该模块在我的代码库中的实际实现如下:
const sharp = require('sharp');
module.exports = class ImageProcessingAdapter {
async processImageWithDefaultConfiguration(buffer, size, options) {
return await sharp(buffer)
.resize(size)
.jpeg(options)
.toBuffer();
}
}
您可以看到该模块使用链式函数 API,这意味着模拟必须让每个函数返回this
.
单元测试本身可以在这里找到:
jest.mock('sharp');
const sharp = require('sharp');
const ImageProcessingAdapter = require('./../../adapters/sharp/ImageProcessingAdapter');
test('Should call module functions with correct arguments', async () => {
// Mock values
const buffer = Buffer.from('a buffer');
const size = { width: 10, height: 10 };
const options = 'options';
// SUT
await new ImageProcessingAdapter().processImageWithDefaultConfiguration(buffer, size, options);
// Assertions
expect(sharp).toHaveBeenCalledWith(buffer);
expect(sharp().resize).toHaveBeenCalledWith(size);
expect(sharp().jpeg).toHaveBeenCalledWith(options);
});
以下是我的嘲笑尝试:
尝试一
// __mocks__/sharp.js
module.exports = jest.genMockFromModule('sharp');
Result
Error: Maximum Call Stack Size Exceeded
尝试二
// __mocks__/sharp.js
module.exports = jest.fn().mockImplementation(() => ({
resize: jest.fn().mockReturnThis(),
jpeg: jest.fn().mockReturnThis(),
toBuffer:jest.fn().mockReturnThis()
}));
Result
Expected mock function to have been called with:
[{"height": 10, "width": 10}]
But it was not called.
Question
如果您能帮助我弄清楚如何正确模拟此第三方模块,我将不胜感激,以便我可以对模拟的调用方式做出断言。
我尝试过使用sinon
and proxyquire
,而且他们似乎也没有完成工作。
再生产
可以找到此问题的单独再现here https://github.com/JamieCorkhill/Reproductions/tree/master/JestMockingIssueRepro.
Thanks.