[英]Mocking a Node Module which uses chained function calls with Jest in Node
请允许我注意, 这里可以找到类似的问题,但是接受的答案解决方案对我不起作用。 还有另外一个问题,答案是建议直接操纵函数的原型,但这同样没有成果。
我试图用Jest来模拟这个名为“sharp”的NPM模块。 它需要一个图像缓冲区并对其执行图像处理/操作操作。
我的代码库中模块的实际实现如下:
const sharp = require('sharp');
module.exports = class ImageProcessingAdapter {
async processImageWithDefaultConfiguration(buffer, size, options) {
return await sharp(buffer)
.resize(size)
.jpeg(options)
.toBuffer();
}
}
您可以看到模块使用链式函数API,这意味着mock必须让每个函数都返回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');
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()
}));
Expected mock function to have been called with:
[{"height": 10, "width": 10}]
But it was not called.
我很感激任何帮助,找出如何正确模拟这个第三方模块,这样我就可以对调用mock的方式做出断言。
我尝试过使用sinon
和proxyquire
,他们似乎也没有完成工作。
可在此处找到此问题的独立复制品。
谢谢。
你的第二次尝试非常接近。
唯一的问题是,每次调用sharp
都会返回一个新的模拟对象,其中包含新的resize
, jpeg
和toBuffer
模拟函数...
...这意味着当您测试resize
时:
expect(sharp().resize).toHaveBeenCalledWith(size);
...你实际上正在测试一个尚未调用的全新resize
模拟函数。
要修复它,只需确保sharp
始终返回相同的模拟对象:
__mocks __ / sharp.js
const result = {
resize: jest.fn().mockReturnThis(),
jpeg: jest.fn().mockReturnThis(),
toBuffer: jest.fn().mockReturnThis()
}
module.exports = jest.fn(() => result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.