在我的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
。
答案 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。
您还可以使用mockImplementation。
如果您在utils.js中有多个函数,并且想要全部模拟它们,我建议您遵循以下文档:https://facebook.github.io/jest/docs/en/manual-mocks.html#mocking-user-modules。只需致电jest.mock('path/to/utils')
请遵循最适合您用例的内容。