【问题标题】:Globally mock a function in Jest/Enzyme in React在 React 中全局模拟 Jest/Enzyme 中的函数
【发布时间】:2019-08-12 23:00:59
【问题描述】:

我经常有一些函数被导入到我想使用 jest/enzyme 测试的 React 组件中。

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

有没有办法使用 jest/enzyme 来定义将在组件测试中使用的全局模拟函数,该函数将覆盖已导入到我正在测试的组件中的同名函数的实现?

【问题讨论】:

  • 如果您觉得需要测试该功能,请单独测试,或将其变成组件上的道具。

标签: reactjs mocking jestjs enzyme


【解决方案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 在 spy 中封装了一个函数,您可以使用它的任何 methods 来更改 spy 的行为方式,例如 mockReturnValuemockImplementation 等。

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

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

【讨论】:

  • 非常感谢!如果我使用 mount 而不是 shallow ,同样的配置会起作用吗?
  • @Dog 是的!一旦像这样模拟一个函数,无论它如何调用,它都会返回模拟值
猜你喜欢
  • 2022-01-19
  • 2020-02-02
  • 2019-05-25
  • 2019-05-12
  • 1970-01-01
  • 2017-03-19
  • 1970-01-01
  • 2021-02-14
  • 2018-11-01
相关资源
最近更新 更多