猛跑小豬
2021-06-30 14:59:21
請(qǐng)?jiān)试S我注意,可以在此處找到與此類(lèi)似的問(wèn)題,但已接受的答案的解決方案對(duì)我不起作用。還有一個(gè)與此類(lèi)似的問(wèn)題,其答案建議直接操作函數(shù)的原型,但這同樣沒(méi)有結(jié)果。我正在嘗試使用 Jest 來(lái)模擬這個(gè)名為“sharp”的 NPM 模塊。它需要一個(gè)圖像緩沖區(qū)并對(duì)其執(zhí)行圖像處理/操作操作。該模塊在我的代碼庫(kù)中的實(shí)際實(shí)現(xiàn)如下:const sharp = require('sharp');module.exports = class ImageProcessingAdapter { async processImageWithDefaultConfiguration(buffer, size, options) { return await sharp(buffer) .resize(size) .jpeg(options) .toBuffer(); }}您可以看到該模塊使用了一個(gè)鏈?zhǔn)胶瘮?shù) API,這意味著模擬必須讓每個(gè)函數(shù) return this。單元測(cè)試本身可以在這里找到: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.jsmodule.exports = jest.genMockFromModule('sharp');結(jié)果Error: Maximum Call Stack Size Exceeded嘗試二// __mocks__/sharp.jsmodule.exports = jest.fn().mockImplementation(() => ({ resize: jest.fn().mockReturnThis(), jpeg: jest.fn().mockReturnThis(), toBuffer:jest.fn().mockReturnThis()}));結(jié)果Expected mock function to have been called with: [{"height": 10, "width": 10}]But it was not called.問(wèn)題我很感激在弄清楚如何正確模擬這個(gè)第三方模塊方面的任何幫助,以便我可以對(duì)調(diào)用模擬的方式做出斷言。我試過(guò)使用sinonand proxyquire,但他們似乎也沒(méi)有完成工作。
1 回答

墨色風(fēng)雨
TA貢獻(xiàn)1853條經(jīng)驗(yàn) 獲得超6個(gè)贊
您的第二次嘗試非常接近。
唯一能與它的問(wèn)題是,每次sharp被稱(chēng)為一個(gè)新的嘲笑對(duì)象返回新的resize,jpeg和toBuffer模擬功能...
...這意味著當(dāng)你這樣測(cè)試時(shí)resize:
expect(sharp().resize).toHaveBeenCalledWith(size);
...您實(shí)際上是在測(cè)試一個(gè)resize尚未調(diào)用的全新模擬函數(shù)。
要修復(fù)它,只需確保sharp始終返回相同的模擬對(duì)象:
__mocks__/sharp.js
const result = {
resize: jest.fn().mockReturnThis(),
jpeg: jest.fn().mockReturnThis(),
toBuffer: jest.fn().mockReturnThis()
}
module.exports = jest.fn(() => result);
添加回答
舉報(bào)
0/150
提交
取消