如何用 jest 和 enzyme 模拟 React 组件方法

How to mock React component methods with jest and enzyme

我有一个 React 组件(这是为了演示问题而简化的):

class MyComponent extends Component {
    handleNameInput = (value) => {
        this.searchDish(value);
    };

    searchDish = (value) => {
      //Do something
    }

    render() {
        return(<div></div>)
    }
}

现在我想测试 handleNameInput() 使用提供的值调用 searchDish

为此,我想创建一个 jest mock function 来替换组件方法。

到目前为止,这是我的测试用例:

it('handleNameInput', () => {
   let wrapper = shallow(<MyComponent/>);
   wrapper.searchDish = jest.fn();
   wrapper.instance().handleNameInput('BoB');
   expect(wrapper.searchDish).toBeCalledWith('BoB');
})

但我在控制台中得到的只是 SyntaxError:

SyntaxError

  at XMLHttpRequest.open (node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:458:15)
  at run_xhr (node_modules/browser-request/index.js:215:7)
  at request (node_modules/browser-request/index.js:179:10)
  at DishAdmin._this.searchDish (src/main/react/components/DishAdmin.js:155:68)
  at DishAdmin._this.handleNameInput (src/main/react/components/DishAdmin.js:94:45)
  at Object.<anonymous> (src/main/react/tests/DishAdmin.test.js:122:24)

所以我的问题是,如何使用酶正确模拟组件方法?

方法可以这样模拟:

it('handleNameInput', () => {
   let wrapper = shallow(<MyComponent/>);
   wrapper.instance().searchDish = jest.fn();
   wrapper.update();
   wrapper.instance().handleNameInput('BoB');
   expect(wrapper.instance().searchDish).toBeCalledWith('BoB');
})

您还需要在被测组件的包装器上调用 .update 以正确注册模拟函数。

语法错误来自错误的分配(您需要将方法分配给实例)。我的其他问题是在模拟方法后没有调用 .update()

@Miha 的回答做了一个小改动:

it('handleNameInput', () => {
  let wrapper = shallow(<MyComponent/>);
  const searchDishMock = jest.fn();
  wrapper.instance().searchDish = searchDishMock;
  wrapper.update();
  wrapper.instance().handleNameInput('BoB');
  expect(searchDishMock).toBeCalledWith('BoB');
})

需要将 wrapper.update(); 替换为 wrapper.instance().forceUpdate();