Nadeem Ahmad
Nadeem Ahmad

Reputation: 745

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

I have a situation where I want to test a function that has been called in an if statement. I don't know how to test this function which actually returns a boolean.

Code

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

In the above snippet, I am trying to test that function, I am able to do that, but can go through the if() branch.

I am using jest and react-testing-library.

I don't have access to the body of the functions within the if statements.

Tried this

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 | 

Upvotes: 0

Views: 3055

Answers (1)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

Try using 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();
});

assuming the functions.start(props) will call your test function.

Upvotes: 1

Related Questions