請允許我注意,可以在此處找到與此類似的問題,但已接受的答案的解決方案對我不起作用。還有一個與此類似的問題,其答案建議直接操作函數(shù)的原型,但這同樣沒有結(jié)果。我正在嘗試使用 Jest 來模擬這個名為“sharp”的 NPM 模塊。它需要一個圖像緩沖區(qū)并對其執(zhí)行圖像處理/操作操作。該模塊在我的代碼庫中的實際實現(xiàn)如下:const sharp = require('sharp');module.exports = class ImageProcessingAdapter { async processImageWithDefaultConfiguration(buffer, size, options) { return await sharp(buffer) .resize(size) .jpeg(options) .toBuffer(); }}您可以看到該模塊使用了一個鏈式函數(shù) API,這意味著模擬必須讓每個函數(shù) return 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.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.問題我很感激在弄清楚如何正確模擬這個第三方模塊方面的任何幫助,以便我可以對調(diào)用模擬的方式做出斷言。我試過使用sinonand proxyquire,但他們似乎也沒有完成工作。
在 Node 中用 Jest 模擬一個使用鏈式函數(shù)調(diào)用的 Node 模塊
猛跑小豬
2021-06-30 14:59:21