测试 return 对象的函数 return 函数 return 布尔值

Testing a function which returns an object that returns a function which return a boolean

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

的函数

代码

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

在上面的代码片段中,我正在尝试测试该功能,我能够做到,但可以通过 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();
    });

But got this error !

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 | 

尝试使用 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 函数。