在React的Jest / Enzyme中全局模拟一个函数

时间:2019-03-22 01:07:29

标签: reactjs mocking jestjs enzyme

通常,我具有导入到React组件中的功能,这些功能我想使用玩笑/酶来进行测试。

通常,我可以通过wrapper.instance()。functionName访问组件中定义的函数,然后测试该函数是否已被调用。类似地,当在测试中安装组件时,我可以传递一个模拟函数作为道具,然后检查该组件是否已被调用。但是,我没有测试导入组件(未在内部定义或作为props)的函数的方法。

是否有一种方法可以使用玩笑/酶来定义将在组件测试中使用的全局模拟功能,该功能将覆盖已导入到我正在测试的组件中的同名功能的实现? / p>

1 个答案:

答案 0 :(得分:1)

是的,有可能。

模拟模块或模块中的各个功能的方法有很多。


这里是一个例子:

lib.js

export const importedFunc = () => 'original';

code.js

import * as React from 'react';
import { importedFunc } from './lib';

export class SimpleComponent extends React.Component {
  render() {
    return (<div>{ importedFunc() }</div>);
  }
}

code.test.js

import * as React from 'react';
import { shallow } from 'enzyme';
import * as lib from './lib';
import { SimpleComponent } from './code';

test('SimpleComponent', () => {
  const spy = jest.spyOn(lib, 'importedFunc');
  spy.mockReturnValue('mocked');
  const wrapper = shallow(<SimpleComponent />);
  expect(wrapper.html()).toBe('<div>mocked</div>');  // Success!
  expect(spy).toHaveBeenCalled();  // Success!
});

jest.spyOn将功能包装在间谍程序中,您可以更改其methodsmockReturnValuemockImplementation的行为方式。

jest.mock可让您模拟整个模块。

Manual mocks允许您创建可在测试中使用的模块模拟​​。

相关问题