首页 > 解决方案 > 酶测试与上下文 api 反应

问题描述

我正在尝试测试表格。提交表单时,它应该设置一个状态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);
  });

不幸的是,它不起作用。我是单元测试的新手,我不知道我是否做对了,我应该如何解决这个问题。

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

标签: reactjsjestjsenzyme

解决方案


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

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(). 尝试阅读有关此主题的酶示例。


推荐阅读