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

时间:2017-01-24 14:00:29

标签: javascript reactjs jestjs enzyme

我有一个反应组件(这是为了证明问题而简化):

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)

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

3 个答案:

答案 0 :(得分:70)

可以用这种方式模拟该方法:

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

答案 1 :(得分:9)

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

答案 2 :(得分:0)

@ 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');
})
相关问题