如何测试异步/等待API调用并更新React状态

时间:2019-06-12 22:30:42

标签: reactjs testing async-await jestjs enzyme

我想在React中测试一个异步点击事件,该事件有两件事: 1.进行API调用以发送POST请求。 2.成功完成发布请求后,更新顶级组件中的状态。

我想知道测试事件按此顺序发生的最佳方法是什么。

我能够使用jest-fetch-mock模拟一个API调用。但是我不确定如何在创建API后 之后测试状态更新是否执行。而且,状态更新是从顶层组件向下传递到此子组件的功能。

在Feedback.jsx中,updateMembershipStatus从另一个名为ManageMembership的组件中向下传递。

// This component saves feedback
class Feedback extends PureComponent {
  // ...

  async handleSubmit (event) {
    event.preventDefault();

    const {otherReason} = this.state,
      {id, updateMembershipStatus} = this.props;

    try {
      // 1. Make an API call
      const saveReason = await MembershipStatusAPI.updateOtherCancelReason(id, otherReason);
      // 2. Update membership status
      updateMembershipStatus("Feedback");
    } catch (error) {
      console.error("Oops, handleSubmit failed!", error);
    }
  }

  render () {
    const {isDisabled, otherReason} = this.state;
    return (
      <div>
        <div>
          Please let us know your feedback
        </div>
        <textarea
          className="feedback-input"
          onChange={this.handleChange}
          value={otherReason}
        />
        <button
          disabled={isDisabled}
          onClick={(e) => this.handleSubmit(e)}
          type="submit"
          value="Submit"
        >
          Cancel my membership
        </button>
      </div>
    );
  }
}

ManageMembership.jsx是顶级组件

class MembershipManagement extends PureComponent {
  // ... 
  constructor (props) {
    super(props);
    this.state = {
      "membershipStatus": this.getCurrentStatus(),
    };
  }

  updateMembershipStatus = (event) => {
    if (event === "Feedback") {
      this.setState({"membershipStatus": "Pending Cancellation"});
    }
  }
}

我的测试,FeedbackTest.jsx

describe("<Feedback /> button", () => {
  let handleSubmit = null,
    wrapper = null;

  const updateOtherCancelReason = (url) => {
    if (url === "google") {
      return fetch("https://www.google.com").then(res => res.json());
    }
    return "no argument provided";
  };

  beforeEach(() => {
    handleSubmit = jest.fn();
    wrapper = mount(
      <Feedback
        disabled
        id={1234567}
      />
    );
    fetch.resetMocks();
  });

    it("should trigger handleSubmit asynchronously: it should call updateOtherCancelReason API first to save comments, then update state", async () => {
    fetch.mockResponseOnce(JSON.stringify({"other_reason": "I am moving to Mars."}));

    wrapper.find("button").simulate("click");

    const callAPI = await updateOtherCancelReason("google");
    expect(callAPI.other_reason).toEqual("I am moving to Mars.");

    expect(fetch.mock.calls.length).toEqual(1);

    // How to test async code here?
  });

以上测试通过了,因为我使用jest-fetch-mock模拟了一个可以给我们模拟响应的API调用。如何测试是否已调用updateMembershipStatus并已成功将ManageMembership.jsx中的状态更新为“待取消”?

另一则类似的帖子:Testing API Call in React - State not updating,但是没有人回答。

1 个答案:

答案 0 :(得分:0)

我将为此使用react-testing-library。如果由于某些异步操作而在屏幕上出现了某些项目,我们可以像这样测试它:

await wait(() => getByText(container, 'some-item'))
// make asserts
相关问题