使用Jest模拟相同模块的不同值

时间:2020-07-01 10:30:47

标签: javascript reactjs unit-testing jestjs

我试图用玩笑来测试react组件,我是新手,所以请原谅任何错误。

我一直在使用此解决方案Jest mock module multiple times with different values,但问题是我的组件结构不同。

代码:test.tsx

import { AccountPage } from "./AccountPage";
import { Store, Symbol } from "store-provider";
   const accountStore = {
   state: {
     fetching: false,
   };

    <Store stores={[ [Symbol, accountStore] ]}>
      <AccountPage />
    </Store>

代码:Account.tsx

import {module} from './modules';
import profile from '/profile';
export const () => {
 {module['case'] && (
  <Profile />
 )
 <div> Hello </div>
}

任何人都可以告诉我如何在玩笑中使用渲染来运行此方案。在链接的问题中,它作为单个返回组件运行。

我想模拟module ['case']为真和假。这样我就可以测试两种情况。

1 个答案:

答案 0 :(得分:2)

考虑到case是可写对象属性,可以对其进行备份和恢复以不影响其他测试:

let originalCase;

beforeEach(() => {
   originalCase = module.case;
});

afterEach(() => {
   module.case = originalCase;
});

it('...', () => {
  module.case = true;
  ...
});

it('...', () => {
  module.case = false;
  ...
});