【问题标题】:Mocking different values for the same module using Jest使用 Jest 模拟同一模块的不同值
【发布时间】:2020-07-01 20:26:52
【问题描述】:

我尝试使用 jest 测试一个反应组件,我是测试新手,所以请原谅任何错误。

我一直在关注这个解决方案 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>
}

谁能告诉我如何使用渲染来运行这个场景。在将其作为单个返回组件运行链接的问题中。

我想将模块['case'] 模拟为真假。所以我可以测试这两种情况。

【问题讨论】:

    标签: javascript reactjs unit-testing jestjs


    【解决方案1】:

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

    let originalCase;
    
    beforeEach(() => {
       originalCase = module.case;
    });
    
    afterEach(() => {
       module.case = originalCase;
    });
    
    it('...', () => {
      module.case = true;
      ...
    });
    
    it('...', () => {
      module.case = false;
      ...
    });
    

    【讨论】:

    • beforeEach 和 afterEach 应该定义在 describe 还是 outside?​​span>
    • 它们可以在内部描述但不应该。 Jest 允许顶级it 等块。
    猜你喜欢
    • 2018-09-13
    • 2020-05-30
    • 2019-08-17
    • 2019-05-22
    • 2021-02-04
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多