Mocking the condition inside code using Jest unit test

Viewed 369

I'm trying to create a unit test using Jest. I have a function that checks the version of the requirement set of Outlook and if the 'set' is supported it does something - in this case, it is closing the add-in.

if (Office.context.requirements.isSetSupported('Mailbox', '1.15') {...}

In the unit test, I tried to mock the external isSetSupported() call values but when running the getCloseAddin() I am getting an error of:

Office.context.requirements.isSetSupported is not a function

It doesn't recognize the mock function I've just created. I've also tried to change the values of the global.Office

global.Office = {
context: {
  requirements: {
   isSetSupported: {'Mailbox', '1.5'}
  }
}

}; but without success.

file.js

const getCloseAddin = () => {
  try {
    const Office = getOffice();
    if (Office.context.requirements.isSetSupported('Mailbox', '1.15')) {
    return Office.context.ui.closeContainer();
  }
} catch (e) {
  console.error('Cannot close the add-in properly.');
  return null;
 }

};

file.test.js

it('verify we gets Undefined when working with supported version', async () => {
  const mockedIsSetSupported = jest.fn();
  mockedIsSetSupported.mockReturnValueOnce('Mailbox', '1.5');
  global.Office = {
    context: {
      requirements: {
        mockedIsSetSupported
      }
    }
  };
  const closeAddin = await getCloseAddin();
  expect(closeAddin).toBeUndefined();
});
1 Answers

I've found the solution for the mock.fn. I wasn't setting the mock.fn in the right place.


const mockedIsSetSupported = jest.fn().mockReturnValue(true);
global.Office = {
    context: {
        requirements: {
            isSetSupported: mockedIsSetSupported,
        },
        ui: {
            closeContainer: () => undefined,
        },
    },
};

Now the isSetSupported function will use the mock.fn instead of the real one and won't crash.

Related