【问题标题】:Testing a function which returns an object that returns a function which return a boolean测试返回对象的函数,该对象返回返回布尔值的函数
【发布时间】:2020-04-23 06:21:33
【问题描述】:

我有一种情况,我想测试一个在if 语句中调用的函数。我不知道如何测试这个实际上返回 boolean 的函数。

代码

function test(){
  if(await SOP3loginConfig(props: object).isSOP3()){
    //calls if statements
  } else {
    //calls else statements
  }
}

在上面的 sn-p 中,我正在尝试测试该功能,我能够做到,但可以通过 if() 分支。

我正在使用jestreact-testing-library

我无权访问 if 语句中的函数体。

试过了

it('Should call the SOP3 functions', () => {
      props.user = {};
      let SOP3loginConfig = (props: any) => {
        console.log(' ========================= I A M A TEST');
        return {
          isSOP3: () => {
            console.log(' ================ iSOP3 called');
            return true;
          },
        };
      };
      functions.start(props);
      expect(SOP3loginConfig(props).isSOP3()).toHaveBeenCalled();
      expect(props.history.push).not.toHaveBeenCalled();
    });

但是出现了这个错误!

expect(received).toHaveBeenCalled()

    Matcher error: received value must be a mock or spy function

    Received has type:  boolean
    Received has value: true

      229 |       };
      230 |       functions.start(props);
    > 231 |       expect(SOP3loginConfig(props).isSOP3()).toHaveBeenCalled();
          |                                               ^
      232 |       expect(props.history.push).not.toHaveBeenCalled();
      233 |     });
      234 | 

【问题讨论】:

    标签: jestjs react-testing-library


    【解决方案1】:

    尝试使用jest.fn

    it('Should call the SOP3 functions', () => {
      props.user = {};
      const isSOP3Mock = jest.fn(() => {
        console.log(' ================ iSOP3 called');
        return true;
      })
      let SOP3loginConfig = (props: any) => {
        console.log(' ========================= I A M A TEST');
        return {
          isSOP3: isSOP3Mock,
        };
      };
      functions.start(props);
      expect(isSOP3Mock).toHaveBeenCalled();
      expect(props.history.push).not.toHaveBeenCalled();
    });

    假设functions.start(props) 将调用您的test 函数。

    【讨论】:

    • 没有成功! ` expect(jest.fn()).toHaveBeenCalled() 预期呼叫数:>= 1 已接呼叫数:0 230 | }; 231 |函数.开始(道具); > 232 |期望(isSOP3Mock).toHaveBeenCalled(); | ^ 233 |期望(props.history.push).not.toHaveBeenCalled(); 234 | }); 235 | `
    • expect(jest.fn()).toHaveBeenCalled() 是什么?您无需在expect 中调用它。您在调用它之前和期望中调用它,检查存储函数的变量是否已被调用。
    • 因为我想跟踪函数是否被调用,或者条件是真还是假!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-29
    • 2015-07-05
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多