如何使用酶测试反应中的形式值?

时间:2018-02-07 09:09:18

标签: reactjs unit-testing enzyme

如何使用jest和酶访问和测试反应中的输入字段?

Container.js

import { getAgent } from "../../reducers/agents";
class AgentForm extends Component {
      componentWillMount = () => {
          //code
          this.agent = getAgent(agents, match.params.id);
      }
      render = () => {
       const agent = this.agent;
       return (
              <article className="thirteen wide column">
              <form className="ui form" onSubmit={this.submit}>
              <div className="field">
          <label htmlFor="newFirstName">First Name</label>
          <input
            type="text"
            tabIndex="10"
            name="newFirstName"
            id="newFirstName"
            placeholder="First Name"
            autoComplete="off"
            autoFocus={true}
            ref={input => (this.firstNameField = input)}
            defaultValue={agent.firstName}
          />
        </div>
        </form>
        </article>
       )
      }
}

我想正确测试输入字段中设置的值。

test.js

 it("should set the form values", () => {
     const form = document.createElement("form"),
     store = configureStore(),
     agent = {
              firstName: "agent1",
              lastName: "abc",
              email: "agent1@email.com",
              active: true,
              admin: true
             },
      name = "newAgent";

      const wrapper = shallow(
            <provider store={store}>
            <AgentForm>
            </AgentForm>
            </provider>
      );
     expect(wrapper.find(".ui form").length).toBe(1);
     });

但我的测试失败了以下消息:

expect(received).toBe(expected)

Expected value to be (using ===):
  1
Received:
  0

而且我还需要测试&#34; defaultValue&#34;输入字段设置为&#34; agent1&#34; (即,来自我的const agent = {firstName:&#34; agent1&#34;})。如何通过这个测试?我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

在测试嵌套组件时,尝试使用酶shallow而不是it("should set the form values", () => { const form = document.createElement("form"), store = configureStore(), agent = { firstName: "agent1", lastName: "abc", email: "agent1@email.com", active: true, admin: true }, name = "newAgent"; const wrapper = mount( <provider store={store}> <AgentForm /> </provider> ); expect(wrapper.find("form").length).toBe(1); }); 。 类似的东西:

mvn compile