【问题标题】:jest/enzyme mock function in functional component功能组件中的玩笑/酶模拟功能
【发布时间】:2019-01-16 06:53:39
【问题描述】:

我有一个函数式组件,我想用模拟函数对其进行测试 (简化演示)

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 无法模拟该函数,因为它超出了范围。 我将如何模拟函数 remove ?

【问题讨论】:

    标签: reactjs mocking jestjs enzyme


    【解决方案1】:

    这是一个工作示例:

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

    【讨论】:

    • 如果remove是一个导入函数怎么办?事情保持不变吗?
    【解决方案2】:

    您应该将remove 函数作为道具传递,而不是仅仅定义一个模块私有的相邻变量。

    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()
    })
    

    【讨论】:

    • 是否可以模拟私有函数?因为这在我的项目中经常发生
    • 覆盖率报告中是否涵盖整个实际功能?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    相关资源
    最近更新 更多