【问题标题】:enzyme testing react with context api酶测试与上下文 api 反应
【发布时间】:2019-06-27 11:50:02
【问题描述】:

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

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

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

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案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()中初始化酶组件。尝试阅读有关此主题的酶示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-30
      • 2017-06-26
      • 2019-09-07
      • 2017-09-24
      • 2018-11-17
      • 1970-01-01
      • 2020-06-01
      • 1970-01-01
      相关资源
      最近更新 更多