typescript - In a React project, after updating MSW, tests return an empty string - Stack Overflow

admin2025-04-04  0

The configuration settings are as follows

vitest.config.js

/// <reference types="vitest" />

import { defineConfig } from "vitest/config";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  test: {
    environment: "jsdom",
    include: ["**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}"],
    globals: true,
    typecheck: {
      tsconfig: "tsconfig.test.json",
    },
    setupFiles: ["./src/app/utils/VitestBootstrap.ts"],
    coverage: {
      provider: "v8",
      include: ["src/**/*.{js,ts}"],
      exclude: [
        "src/**/__mocks__/**",
        "src/**/{models,providers,utils,data}/**",
      ],
      all: true,
      reporter: ["html", "clover", "text"],
    },
  },
});

VitestBootstrap.ts

import "@testing-library/jest-dom";
import "jest-extended";
import "whatwg-fetch";

import { server } from "./mocks/server";

import { vi } from "vitest";

vi.mock("next/config", () => {
  const getConfig = {
    publicRuntimeConfig: {
      baseURL: {
        myapp: ";,
      },
    },
  };
  return { default: () => getConfig };
});

beforeAll(() => server.listen({ onUnhandledRequest: "error" }));
afterAll(() => server.close());
afterEach(() => server.resetHandlers());

server.ts

export const handlers = [
    http.post("/test/:id", () =>
        HttpResponse.json(samplePostSuccess, { status: 200 }),
    ),
];

export const server = setupServer(...handlers);

And the bottom part is the part that I did

export const axiosGetGen = (axiosInstance: AxiosInstance) => {
  return async <T>(
    path: string,
    init: RawAxiosRequestHeaders = {},
  ): Promise<T> => {
    return axiosRawGetGen(axiosInstance)<T>(path, init).then((res) => res.data);
  };
};

export const axiosRawGetGen = (axiosInstance: AxiosInstance) => {
  return async <T>(
    path: string,
    init: RawAxiosRequestHeaders = {},
  ): Promise<AxiosResponse<T>> => {
    return axiosInstance.get<T>(path, { headers: init, withCredentials: true });
  };
};

export const axiosInstance: AxiosInstance = axios.create({
    baseURL: BASE_URL,
    timeout: publicRuntimeConfig.requestTimeout,
});
it("test", async () => {
  const axiosGet = axiosGetGen(axiosInstance);
  const expected = { success: true };
  let cookies;
  server.use(
    http.get("/test", async ({ cookies: ck }) => {
      cookies = ck;
      return HttpResponse.json({ data: expected }, { status: 200 });
    }),
  );
  document.cookie = "testCookie=value";
  const actual = await axiosGet("/test");

  expect(cookies).toEqual({ testCookie: "value" });
  expect(actual).toEqual(expected); // Failed to return empty string
});

In the actual result, { success: true } should be returned, but an empty string "" is being returned.

I'm using axios 1.8.2, and I updated msw from 1.2.2 to 2.7.3. After the update, I replaced rest.get with http.get, HttpResponse.json, etc.

However, when I ran the tests, I encountered this issue (it was working fine before the update).

If I don't use axios, the result comes out correctly. But if I use axios, is there any specific setting required to make it work?

Below are some things that seemed related... .x-to-2.x/#frequent-issues

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1743736795a216879.html

最新回复(0)