开玩笑如何在从表单向服务器提交数据时测试错误?

时间:2018-10-27 02:51:43

标签: reactjs jestjs enzyme moxios

考虑以下代码:

class Dashboard extends Component {
  state = {
    fileName: "",
    group: "",
    country: "",
    error: ""
  };
  onFormSubmit = async e => {
    e.preventDefault();
    const { group, country } = e.target;
    try {
      await axios.post("/api/dashboard", {
        name: group.value,
        country: country.value,
        image: this.state.fileName
      });
    } catch (error) {
      console.log(error.response.data.message);
      this.setState({ error: error.response.data.message });
    }
  };

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

当发布请求失败时,我正在尝试将error状态设置为适当的值。到目前为止,这是测试:

  it("should set error state when dashboard api returns error", async () => {
    const errorMsg = "Group already exist";
    moxios.stubRequest("/api/dashboard", {
      status: 400,
      response: {
        message: errorMsg
      }
    });
    const event = {
      preventDefault: () => {},
      target: {
        group: "",
        country: ""
      }
    };
    const wrapper = shallow(<Dashboard />);
    await wrapper.find("form").simulate("submit", event);
    console.log(wrapper.state("error").value);
    expect(wrapper.state("error")).toBe(errorMsg);
  });

1 个答案:

答案 0 :(得分:1)

由于方法onformSubmitasync,因此您可以在此处使用几种方法:

1 直接等待异步方法:

it(
  'should set error state when dashboard api returns error',
  async () => {
    const wrapper = shallow(<Dashboard />);
    await wrapper.instance().onFormSubmit(event);
    expect(wrapper.state('error')).toBe(errorMsg);
  }
);

并分别测试是否在onFormSubmit事件中调用了方法submit

2 使用超时并返回Promise

it(
  'should set error state when dashboard api returns error',
  () => {
    const wrapper = shallow(<Dashboard />);
    wrapper.find("form").simulate("submit", event);
    return new Promise(resolve => setTimeout(resolve, 1)).then(() => {
      expect(wrapper.state('error')).toBe(errorMsg);
    });
  },
  1000
);

3 等待打勾,然后再检查:

function tick() {
  return new Promise(resolve => {
    setTimeout(resolve, 1);
  });
}

...

it('should set error state when dashboard api returns error', async () => {
  const wrapper = shallow(<Dashboard />);
  wrapper.find('form').simulate('submit', event);
  await tick();
  expect(wrapper.state('error')).toBe(errorMsg);
});

4 使用done回调:

it('should set error state when dashboard api returns error', done => {
  const wrapper = shallow(<Dashboard />);
  wrapper.find('form').simulate('submit', event);
  setImmediate(() => {
    expect(wrapper.state('error')).toBe(errorMsg);
    done();
  });
});