第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Node 中用 Jest 模擬一個使用鏈式函數(shù)調(diào)用的 Node 模塊

在 Node 中用 Jest 模擬一個使用鏈式函數(shù)調(diào)用的 Node 模塊

猛跑小豬 2021-06-30 14:59:21
請允許我注意,可以在此處找到與此類似的問題,但已接受的答案的解決方案對我不起作用。還有一個與此類似的問題,其答案建議直接操作函數(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,但他們似乎也沒有完成工作。
查看完整描述

1 回答

?
墨色風雨

TA貢獻1853條經(jīng)驗 獲得超6個贊

您的第二次嘗試非常接近。


唯一能與它的問題是,每次sharp被稱為一個新的嘲笑對象返回新的resize,jpeg和toBuffer模擬功能...


...這意味著當你這樣測試時resize:


expect(sharp().resize).toHaveBeenCalledWith(size);

...您實際上是在測試一個resize尚未調(diào)用的全新模擬函數(shù)。


要修復(fù)它,只需確保sharp始終返回相同的模擬對象:


__mocks__/sharp.js


const result = {

  resize: jest.fn().mockReturnThis(),

  jpeg: jest.fn().mockReturnThis(),

  toBuffer: jest.fn().mockReturnThis()

}


module.exports = jest.fn(() => result);


查看完整回答
反對 回復(fù) 2021-07-01
  • 1 回答
  • 0 關(guān)注
  • 216 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號