如何在酶中使用refs测试不受控制的表单?

时间:2018-12-07 17:20:51

标签: reactjs jestjs enzyme

我正在尝试使用React + Enzyme + Jest测试我的注册表单。我的注册表单上有一个引用,供以后用来验证输入,但是输入都是不受控制的。我想确保在不更新任何输入的情况下,验证不会通过,并且不会调用我的async方法。 在render()中:

<form name="signup" ref={(e) => { this.form = e; }} onSubmit={this.handleSignup}>
  <TextField
    label="Company Name"
    name="companyName"
    id="companyName"
  />
  .
  .
  .
</form>

handleSignup中,我正在提取值并验证它们:

const values = [
  { companyName: this.form.companyName.value },
  .
  .
  .
];
this.validate(values);

当我mount在酶和simulate('submit')中的成分时,我的引用中没有任何输入值,给了我Error: Uncaught [TypeError: Cannot read property 'value' of undefined]

expect(wrapper.instance().form).toBeDefined(); //passes, so this.form is defined
expect(wrapper.instance().form.companyName).toBeDefined(); // fails
expect(wrapper.ref('form')).toBeDefined(); //fails

如果我将ref更改为字符串ref,

expect(wrapper.ref('form')).toBeDefined(); //passes
expect(wrapper.ref('form').companyName).toBeDefined(); //fails

全面测试:

it('should not submit with no inputs', () => {
    const createAccount = sinon.spy();
    const wrapper = mount(
      <Signup
        auth={{
          status: 'pristine',
        }}
        createAccount={createAccount}
        match={{}}
      />,
    );

    wrapper.setProps({});
    expect(wrapper.ref('form')).toBeDefined();
    expect(wrapper.ref('form').companyName).toBeDefined();

    expect(createAccount).to.have.property('callCount', 0);
});

Github Issue with minimal repo and codesandbox link

0 个答案:

没有答案