酶 - 用于组件的模拟工具功能

时间:2018-04-23 14:46:47

标签: reactjs unit-testing jestjs enzyme

在我的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

2 个答案:

答案 0 :(得分:3)

您可以使用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')
})

答案 1 :(得分:1)

您只需在测试文件中执行以下操作:

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

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

请遵循最适合您用例的内容。

相关问题