簡體   English   中英

Jest spyOn函數不是Class或Object類型

[英]Jest spyOn a function not Class or Object type

我熟悉在Class或Object方法上設置間諜,但是當函數只是一個導出默認值時 - 這樣方法本身是獨立的,就像實用程序一樣?

我有一些像這樣的現有代碼:

const Funct1 = props => {
  if(props){
    Funct2(args);
  }
  // or return something
};
const Funct2 = props => {
  // do something
  return true
};
export default Funct1;  //Yes the existing export is named the same as the "entry" method above.

而且,例如,我想監視Funct1被調用而Funct2返回true。

import Funct1 from "../../../src/components/Funct1";
describe("Test the Thing", () => {
    it("New Test", () => {
        let props = {
            active: true,
            agentStatus: "online"
        };
        const spy = spyOn(Funct2, "method name"); <-- how doe this work if not an obj or class?

        Funct1(props);
        //If I try Funct2(props) instead, terminal output is "Funct2 is not defined"

        expect(spy).toHaveBeenCalledWith(props);
    });
});

我不是開玩笑的專家,但我的建議是考慮:

1)當函數導出為默認值時,我使用如下內容:

import Funct1 from "../../../src/components/Funct1";
...
jest.mock("../../../src/components/Funct1");
...
expect(Funct1).toHaveBeenCalledWith(params);

2)當模塊(utils.js)有多個導出為

export const f1 = () => {};
...
export const f8 = () => {};

你可以試試

import * as Utils from "../../../src/components/utils"
const f8Spy = jest.spyOn(Utils, 'f8');
...
expect(f8Spy).toHaveBeenCalledWith(params);

這里類似的討論

我相信無法在不修改現有代碼的情況下測試Funct1調用Funct2。 如果后者是一個選項,這里有兩個引入依賴注入的選項:

  • 創建和導出工廠功能:

     const Funct2 = props => { // do something return true; }; const Funct1 = CreateFunct1(Funct2); export function CreateFunct1(Funct2) { return props => { if (props) { Funct2(props); } // or return something }; } export default Funct1; // and here is the test: describe('Test the Thing', () => { it('New Test', () => { // Arrange const funct2Spy = jasmine.createSpy('Funct2'); const funct1 = CreateFunct1(funct2Spy); const props = "some data"; // Act funct1(props); // Assert expect(funct2Spy).toHaveBeenCalledWith(props); }); }); 
  • 導出Funct2也是。 這里是一個線程在這個題目。 由於導出語法,也許它的示例必須針對您的場景稍微調整一下。

暫無
暫無

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

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