酶测试与上下文API反应

时间:2019-06-27 11:50:02

标签: reactjs jestjs enzyme

我正在尝试测试表格。提交表单后,应在error: true上设置状态,然后出现带有错误信息的div。我的测试如下:

 outer = shallow(<Search />);

 it("should not submit a form and display an error if title or author is empty", () => {
    const Children = outer.props().children({});
    const wrapper = mount(Children);
    const button = wrapper.find("form button");
    button.simulate("submit", {
      preventDefault() {
        outer.setState({ error: true });
      }
    });
    expect(wrapper.find("div.error")).toHaveLength(1);
  });

不幸的是,它不起作用。我是单元测试的新手,我不知道自己是否做得正确以及应该如何解决。

我想我也应该以某种方式获得输入值,但不知道如何。

1 个答案:

答案 0 :(得分:1)

这是为输入元素设置值的示例:

it('Should capture firstname correctly onChange', function(){
    const component = mount(<Form />);
    const input = component.find('input').at(0);
    input.instance().value = 'hello';
    input.simulate('change');
    expect(component.state().firstname).toEqual('hello');
})

但是由于其他原因,它可能不起作用,请确保已初始化beforeAll()中的酶成分。尝试阅读有关该主题的酶实例。