0

我已经创建了一个基本的 React 应用程序并按照设置单元测试(节点环境)和浏览器的说明配置了 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 天时间四处挖掘并试图找出配置中是否有问题或自定义钩子或组件的编写方式。

4

1 回答 1

1

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

于 2020-12-27T23:33:34.077 回答