【问题标题】:React Jest tests failing with MSWReact Jest 测试因 MSW 失败
【发布时间】:2021-04-04 10:29:24
【问题描述】:

我创建了一个basic React application 并在instructions 之后配置了 MSW 以设置单元测试(节点环境)和浏览器

App 组件使用自定义钩子useFormSubmission 并呈现带有用户名文本字段和提交按钮的简单表单。表单的提交处理程序使用自定义挂钩返回的回调。

目前所有的单元测试都失败了。我可以看到 MSW 收到请求,但没有看到任何回复。控制台记录了减速器状态Status: pending,但并没有超出这个范围(似乎响应被吞没/丢失了?)奇怪的是,该应用程序在与开发服务器npm start 一起运行时工作。

const useFormSubmissionReducer = (state, action) => {
  switch (action.type) {
    case "start":
      return { status: "pending" };
    case "resolved":
      return { status: "resolved", data: action.data };
    case "rejected":
      return { status: "rejected", error: action.error };
    default:
      throw new Error(`Unsupported type: ${action.type}`);
  }
};

const handleResponse = async (response) => {
  const data = await response.json();

  if (response.status >= 200 && response.status <= 299) {
    return Promise.resolve(data);
  } else {
    return Promise.reject(data);
  }
};

const useFormSubmission = () => {
  const [state, dispatch] = useReducer(useFormSubmissionReducer, {
    status: "idle",
    data: null,
    error: null,
  });

  const callback = useCallback((request) => {
    const payload = JSON.stringify(request);

    console.log("Dispatching: ", request);
    dispatch({ type: "start" });

    fetch("/api/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: payload,
    })
      .then(handleResponse)
      .then(
        (data) => {
          console.log("Data: ", data);
          dispatch({ type: "resolved", data });
        },
        (error) => {
          console.log("Error: ", error);
          dispatch({ type: "rejected", error });
        }
      )
      .catch((error) => {
        console.log("Exception: ", error);
        dispatch({ type: "rejected", error: { message: error.message } });
      });
  }, []);

  return [state, callback];
};

我花了 3 天时间四处挖掘,试图找出配置中是否有问题,或者自定义挂钩或组件的编写方式是否有问题。

【问题讨论】:

    标签: javascript reactjs jestjs msw


    【解决方案1】:

    事实证明,测试执行得非常快,最终出现了竞争条件。我添加了await waitForElementToBeRemoved(screen.getByText(&lt;element you are looking for&gt;)),现在所有测试都通过了。

    【讨论】:

      猜你喜欢
      • 2022-06-16
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 1970-01-01
      • 2023-03-08
      • 2018-06-03
      相关资源
      最近更新 更多