开玩笑如何测试表单提交反应?

时间:2018-10-26 05:20:49

标签: reactjs jestjs enzyme

请考虑以下组件:

import React, { Component } from "react";
import ImageUpload from "./ImageUpload/ImageUpload";
import axios from "axios";
class Dashboard extends Component {
  state = {
    fileName: ""
  };

  onFormSubmit = e => {
    e.preventDefault();
    const { group, country } = e.target;
    axios.post("/api/dashboard", {
      name: group.value,
      country: country.value,
      image: this.state.fileName
    });

    //TODO redirect the user
  };

  onFileNameChange = name => {
    this.setState({ fileName: name });
  };
  render() {
    return (
      <div>
        <form onSubmit={this.onFormSubmit}>
          <input type="text" name="group" placeholder="Group Name" />
          <input type="text" name="country" placeholder="Country" />
          <ImageUpload
            fileName={this.state.fileName}
            onFileNameChange={this.onFileNameChange}
          />
          <button type="submit">Add Group</button>
        </form>
      </div>
    );
  }
}

export default Dashboard;

我正在尝试伪造表单的提交并测试何时调用onFormSubmit。我使onFormSubmit成为间谍函数。但是,它根本没有被调用。

import React from "react";
import Dashboard from "components/admin/Dashboard/Dashboard";
import { shallow, render } from "enzyme";

describe("The Dashboard component", () => {
  it("should not regress", () => {
    const wrapper = render(<Dashboard />);
    expect(wrapper).toMatchSnapshot();
  });

  it("should submit the form and send the group to server", () => {
    const wrapper = shallow(<Dashboard />);
    const preventDefault = jest.fn();
    const event = {
      preventDefault,
      target: {
        group: "Samrat",
        country: "Nepal"
      }
    };
    wrapper.instance().onFormSubmit = jest.fn();
    wrapper.update();
    wrapper.find("form").simulate("submit", event);
    expect(wrapper.instance().onFormSubmit).toHaveBeenCalledWith(event);
  });
});

0 个答案:

没有答案