【问题标题】:Mocking the condition inside code using Jest unit test使用 Jest 单元测试模拟代码中的条件
【发布时间】:2020-11-22 15:50:04
【问题描述】:

我正在尝试使用 Jest 创建一个单元测试。 我有一个函数可以检查 Outlook 需求集的版本,如果支持“集合”,它会做一些事情 - 在这种情况下,它正在关闭加载项。

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

在单元测试中,我尝试模拟外部 isSetSupported() 调用值,但是在运行 getCloseAddin() 时出现以下错误:

Office.context.requirements.isSetSupported 不是函数

它无法识别我刚刚创建的模拟函数。 我还尝试更改 global.Office

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

}; 但没有成功。

文件.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();
});

【问题讨论】:

    标签: javascript jestjs outlook-addin outlook-web-addins


    【解决方案1】:

    我找到了 mock.fn 的解决方案。我没有将 mock.fn 设置在正确的位置。

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

    现在 isSetSupported 函数将使用 mock.fn 而不是真实的并且不会崩溃。

    【讨论】:

    • 正确的方法是使用mockReturnValue - isSetSupported: jest.fn().mockReturnValue(true)
    猜你喜欢
    • 2021-10-13
    • 2021-11-05
    • 2022-06-15
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    相关资源
    最近更新 更多