功能组件中的玩笑/酶模拟功能

时间:2018-08-08 22:07:15

标签: 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无法模拟该函数,因为该函数超出范围。 我将如何模拟删除功能?

3 个答案:

答案 0 :(得分:1)

您应该将需要测试的功能代码移到组件之外,然后将这些功能作为道具传递。这样,您可以通过将它们作为道具传递来模拟测试中的功能,从而使组件代码更可重用。

答案 1 :(得分:0)

您应该将remove函数作为prop传递,而不仅仅是定义模块专有的相邻变量。

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

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

答案 2 :(得分:0)

这是一个有效的示例:

// ---- 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作为道具是一种更好的方法。它更容易测试,并使您的组件更可重用。