簡體   English   中英

使用jest.mock時如何猴子修補單個方法

[英]How to monkey patch a single method when using jest.mock

我正在使用Jest測試導入第三方庫的JS項目。 通過在測試文件的頂部執行此操作,我已經能夠成功模擬第三方庫:

jest.mock('third-party');

但是現在,我需要自定義第三方庫中單個方法的模擬實現。 讓我們來說明一下第三方庫的結構,因為我認為這就是我的絆腳石:

第三方圖書館配套

  • 出口建築商1
    • 屬性
    • 大量的實例方法...
  • 出口建築商2
    • 屬性...
    • 實例方法
    • instance methodB <- This is what I want to monkey patch.

我想猴子修補此問題,因為模擬該庫目前在測試中為我提供了這一點:

import { Constructor2 } from 'third-party';

jest.mock('third-party');

describe('Thing', () => {

   var instance 

   beforeEach(() => {
      instance = new Thing();
      instance.constuctor2instance = new Constructor2();
      instance.controls = instance.constuctor2instance.methodB(); 
     // methodB returns nothing because it's mocked. I want it to return a custom implementation. 
   });

   test('test 1', () => {
      // Fake test just for example
      expect(instance.constuctor2instance).toBeInstanceOf(Constructor2); // Success

      jest.spyOn(instance.controls, 'nestedFunction'); // Fails because instance.controls is undefined  
   });
});

因此,如何在定義整個第三方庫甚至整個Constructor2的實現的情況下為methodB提供自定義實現?

**使用** @Teneff從下面的解決方案進行編輯


   jest.mock('third-party');

   const mockControls = {
     nestedFunction: jest.fn()
   };

    beforeEach(() => {
        Constructor2.prototype.controls.mockImplementation(() => mockControls);
    });

    afterEach(() => {
        jest.resetAllMocks();
    });

您可以像這樣使用Constructor2的原型

const mockControls = {
  nestedFunction: jest.fn(),
};

Constructor2.prototype.methodB.mockImplementation(() => mockControls);

而且您不必監視它,就可以這樣聲明:

expect(mockControls.nestedFunction).toHaveBeenCalledWith(...);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM