无法使用Jest覆盖React/Typescript尝试捕获中的行

5kgi1eie  于 2023-02-20  发布在  Jest
关注(0)|答案(1)|浏览(206)

我在React/TypeScript中有以下代码:

const logUser = async () => {
    console.log(`Logging: ${email} - ${password}`);
    try {
      const res = await axios({
        method: "post",
        url: `${process.env.REACT_APP_BASE_URL}/api/auth`,
        headers: {
          "Content-Type": "application/json",
          "Accept-Language": localStorage.getItem("i18nextLng"),
        },
        data: {
          email: email,
          password: password,
        },
      });

      const user = buildUserData(res.data.data);
      saveUserData(user.name, user.email, user.roles, user.token);
      setDismissAlert(true);
      console.log(res.data);
      login().then(() => navigate("/dashboard/overview"));
    } catch (err: any) {
      if (err.response?.data.otp) {
        navigate("/otp", { state: { email: email, password: password } });
      } else if (err.data?.data.message) {
        setLoginError(err.data?.data.message);
        setDismissAlert(false);
      } else {
        setLoginError(t("login.validation.loginError"));
        setDismissAlert(false);
      }
    }
  };

在我的测试中,除了axios.post.mockResolvedValueOnce();返回成功请求所期望的内容,下面几行内容就不包括在内:

const user = buildUserData(res.data.data);
    saveUserData(user.name, user.email, user.roles, user.token);
    setDismissAlert(true);
    console.log(res.data);
    login().then(() => navigate("/dashboard/overview"));

我尝试用这种方式返回模拟数据:

const mockResponse = {
       data: {
         user: {
           id: 1,
           name: "user",
           email: "user@mail.com",
           email_verified_at: null,
           created_at: "2022-12-27T17:10:23.000000Z",
           updated_at: "2022-12-27T17:10:29.000000Z",
           deleted_at: null,
           last_login_at: "2022-12-27T17:10:29.301355Z",
           roles: ["user"],
         },
         token: {
           access_token: "1|Buc8kgCTGFzHdS2HU11ZmWS30SEXHEiLCEQGbBnH",
           token_type: "Bearer",
         },
       },
     };

在我的测试中:

axios.post.mockResolvedValueOnce(mockResponse);

但这不会解决未覆盖的行。
我需要做些什么来覆盖try块(而不是catch)中axios请求之后的行?

wnvonmuf

wnvonmuf1#

试试这个-而不是使用这个API:

const res = await axios({
        method: "post",
        url: `${process.env.REACT_APP_BASE_URL}/api/auth`,

使用此:

const res = await axios.post(`${process.env.REACT_APP_BASE_URL}/api/auth`, {...

然后在测试中:

import axios from "axios";

jest.mock("axios");

it('some test', async () => {
   axios.post.mockResolvedValueOnce(mockResponse);
   // here your test
});

相关问题