jest.isolateModules()是否不隔离我的状态上下文提供程序组件? (反应)

时间:2019-05-16 03:10:57

标签: unit-testing testing jestjs

我将测试组件包装在<StateProvider>组件中,该组件是应用程序状态的上下文提供程序。

为了防止测试组件在测试之间更改状态并确保所有测试都以相同的初始状态开始,我尝试在jest.isolateModules()组件上使用<StateProvider>。由于我的测试由于两次测试之间的状态变化而失败,因此无法正常工作。

以下是每个测试所使用的包装器组件的相关代码:

const AllTheProviders = ({ children }) => {
  let myStateProvider;
  jest.isolateModules(() => {
    myStateProvider = require('./components/state')
  });
  const { StateProvider } = myStateProvider
  return (
    <StateProvider>
      {children}
    </StateProvider>
  );
};

我在此处有一个示例存储库:https://github.com/TidyIQ/rtl_test_failure/

如果运行测试,则控制台中的输出为(为清晰起见而格式化):

  running first click test 1 ***************************
    component receives 'showPassword' state as: false
    first click
    returning 'showPassword' state as: true
    component receives 'showPassword' state as: true
  END OF TEST :::::::::::::::::::::::::::::::::::

  running first click test 2 ***************************
    component receives 'showPassword' state as: true    // <<<< ISSUE IS HERE
    first click
    returning 'showPassword' state as: false
    component receives 'showPassword' state as: false

  running second click test 1 ***************************
    component receives 'showPassword' state as: false
    first click
    returning 'showPassword' state as: true
    component receives 'showPassword' state as: true
    second click
    returning 'showPassword' state as: false
    component receives 'showPassword' state as: false
  END OF TEST :::::::::::::::::::::::::::::::::::

  running second click test 2 ***************************
    component receives 'showPassword' state as: false
    first click
    returning 'showPassword' state as: true
    component receives 'showPassword' state as: true
    second click
    returning 'showPassword' state as: false
    component receives 'showPassword' state as: false
  END OF TEST :::::::::::::::::::::::::::::::::::

我突出显示了问题所在。运行第一个测试后,组件接收showPassword状态为false,这是默认值,但是它收到的状态值与上一个测试返回的状态值相同(true

由于<StateProvider>组件在每个测试中都是隔离的,所以我希望每个测试的状态都将重置,但是您可以看到情况并非如此。

我无法弄清楚我在这里做错了什么。有人有见识吗?

0 个答案:

没有答案