【问题标题】:Mocking exported const in react.js jest在 react.js 笑话中模拟导出的 const
【发布时间】:2021-09-19 06:01:36
【问题描述】:

我正在使用 Mount 在 Jest 中测试一个 React 组件。该组件使用另一个名为 utils.tsx 的 ts 文件中的 const 对象

该组件在单独运行时工作正常,但在使用 jest 安装时出错。 关于如何模拟 const 对象的任何想法?

//utils.tsx

export const params = {
   isEnabled: true,
   cluster_name: 'some cluster'
}

// React component cluster.tsx

import {params} from 'utils';

somefunc = () => {
   // works when running the application
   console.log(params.cluster_name);
}

// Test file

// This test throws - cannot access property cluster_name of undefined
describe('Should print cluster name', () => {
   mount(
     <Provider> 
         <Cluster/>
     </Provider>
   );
})



【问题讨论】:

    标签: reactjs jestjs ts-jest


    【解决方案1】:
    jest.mock('utils.tsx', () => ({
      params: {
        isEnabled: false,
        cluster_name: 'mock cluster'
      }
    }));
    
    describe('Should print cluster name', () => {
       mount(
         <Provider> 
             <Cluster/>
         </Provider>
       );
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多