【问题标题】:Enzyme - Mocking utils function used in a componentEnzyme - 组件中使用的模拟 utils 函数
【发布时间】:2018-04-23 14:46:46
【问题描述】:

在我的 React 应用程序中,我想测试一个从另一个文件调用 utils 函数的组件。 在特定情况下,我确实想模拟这个结果。如何使用 Enzyme 和 Jest 做到这一点?

这是代码:

// MyComponent
import React from 'react';
import { getCalculatedValue } from '../utils';

export class MyComponent extends React.Component {
  constructor(props) {
    const calculatedValue = getCalculatedValue();
    // ...
  }
  // ...
}

还有测试:

// MyComponent test
describe('MyComponent ', () => {
  it('should be...', () => {
    const myComponent= shallow(
        <MyComponent />
    )
    expect(myComponent.find('....').length).toBeDefined()
  })
})

我要模拟的方法是getCalculatedValue

【问题讨论】:

    标签: reactjs unit-testing jestjs enzyme


    【解决方案1】:

    你可以像这样使用jest.mock模拟模块,注意'../utils'的路径是相对于测试文件的:

    jest.mock('../utils', ()=>({getCalculatedValue: ()=> 'someValue'}))
    

    如果您需要使用 getCalculatedValue 的不同返回值模拟模块,您需要使用 jest.fn() 模拟模块,将其导入您的测试并更改测试中的实现:

    jest.mock('../utils', ()=>({getCalculatedValue: jest.fn()}))
    import { getCalculatedValue } from '../utils';
    
    
    it('test1',()=>{
       getCalculatedValue. mockReturnValue('someValue')
    })
    
    
    it('test2',()=>{
       getCalculatedValue. mockReturnValue('anotherValue')
    })
    

    【讨论】:

      【解决方案2】:

      您可以在测试文件中简单地执行以下操作:

      getCalculatedValue = jest.fn().mockReturnValue(YOUR_RETURN_VALUE);
      

      现在,当您使用 shallow 创建组件树时,getCalculatedValue 将始终返回 YOUR_RETURN_VALUE。

      请遵循最适合您的用例的方法。

      【讨论】:

        猜你喜欢
        • 2020-02-02
        • 1970-01-01
        • 1970-01-01
        • 2019-04-10
        • 2019-08-12
        • 1970-01-01
        • 1970-01-01
        • 2017-12-18
        • 2020-12-13
        相关资源
        最近更新 更多