reactjs - 功能组件中的 Jest/ enzyme 模拟功能

标签 reactjs mocking jestjs enzyme

我有一个功能组件,我想用模拟功能测试它 (简化演示)

const remove = () => {
  ... do something
}

const removeButton = (props) => (
  <Button onClick={() => remove()}>
    Remove
  </Button>
);

我尝试过这个测试用例

it('test remove button', () => {
  const test = shallow(<removeButton/>)
  const mockFunction = jest.fn()
  test.instance().remove = mockFunction
  test.find('Button').simulate('click')
  expect(mockFunction).toHaveBeenCalled()
})

.instance().remove 无法模拟该函数,因为它超出了范围。 我如何模拟删除函数?

最佳答案

这是一个工作示例:

// ---- comp.js ----
import * as React from 'react';
import * as comp from './comp';

export const remove = () => {
  // ...do something
}

export const RemoveButton = (props) => (
  <div onClick={() => comp.remove()}>
    Remove
  </div>
);


// ---- comp.test.js ----
import * as React from 'react';
import { shallow } from 'enzyme';

import * as comp from './comp';

describe('removeButton', () => {
  it('should call remove on click', () => {
    const mock = jest.spyOn(comp, 'remove');
    mock.mockImplementation(() => {});
    const component = shallow(<comp.RemoveButton />);
    component.find('div').simulate('click');
    expect(mock).toHaveBeenCalled();
    mock.mockRestore();
  });
});

请注意,要模拟remove,您需要将其导出,并且需要将模块导入回自身并在组件中使用导入。

话虽如此,我同意将 remove 作为 prop 传入是一种更好的方法。它更容易测试,并使您的组件更可重用。

关于reactjs - 功能组件中的 Jest/ enzyme 模拟功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51756316/

相关文章:

reactjs - 正确的代码流: dispatch actions and block, 还是 dispatch 他们提前验证?

reactjs - react 条件渲染

javascript - ReactJS 如何有效地知道要更新 DOM 的哪个子集?

python - 如何模拟未从 __init__ 文件中公开的函数?

python - Python模拟中的模拟属性?

typescript - 如何配置 Jest 以转换包含无效语法的模块?

javascript - React 姿势状态影响子组件姿势

java - 测试包含模拟 JPA 存储库的服务时出现 NullPointerException

javascript - 如何为另一个函数中的函数编写测试用例?

node.js - 开 Jest : child_process. exec.mockImplementation 不是一个函数