【问题标题】:How to test async/await API calls and update React state如何测试 async/await API 调用和更新 React 状态
【发布时间】:2019-10-27 11:55:14
【问题描述】:

我想在 React 中测试一个异步点击事件,它做了两件事: 1. 调用 API 发送 POST 请求。 2. post请求成功后,更新顶级组件的状态。

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

我能够使用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,不过没有人回答。

【问题讨论】:

    标签: reactjs testing async-await jestjs enzyme


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-07
      • 2018-10-11
      • 2020-03-30
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多