openapi-typescript icon indicating copy to clipboard operation
openapi-typescript copied to clipboard

Requests made by client can't be intercepted by msw in testing environment if client is created before msw server starts listening

Open CharlieZhuo opened this issue 1 year ago • 7 comments

Description

I was writing composable unit test in my Vue application. The composable import a openapi-fetch client to make API request. The test uses msw to intercept requests and respond with mock data.

I find out that I can not use the client created(or imported) Before the msw server start listening, or the requests made by the client won't be intercepted. Create and use the client After the server start listening solves the problem.

Reproduction

Run the following unit test. If reCreateClient() isn't called in the beforeAll() after msw server start listening, the test will fail.

import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { http, HttpResponse } from "msw";
import { setupServer } from "msw/node";
import createClient, { Client } from "openapi-fetch";
import type { paths } from "./schema"; // generated by openapi-typescript

const baseUrl = import.meta.env.VITE_API_BASE_URL as string | undefined;

let ApiClient: Client<paths> = createClient({
  baseUrl,
});

function reCreateClient() {
  ApiClient = createClient({
    baseUrl,
  });
}
const mockTags = ["tag1", "tag2", "tag3"];
const server = setupServer(
  http.get(`${baseUrl}/tags`, () => {
    return HttpResponse.json({ tags: mockTags });
  })
);

beforeAll(() => {
  server.listen({ onUnhandledRequest: "error" });
  // recreate the client after the server is set up
  // otherwise server won't be able to intercept the request
  reCreateClient();
});
afterEach(() => {
  server.resetHandlers();
});
afterAll(() => {
  server.close();
});

describe("apiClient", () => {
  it("should fetch articles", async () => {
    const result = await ApiClient.GET("/tags").then(({ data }) => {
      return data;
    });
    expect(result!.tags).toEqual(mockTags);
  });
});

Expected result

I am not sure if it is intended behavior, and what causes it. I would like see some heads-up in the testing document page to prevent test failure caused by this.

Checklist

CharlieZhuo avatar Aug 25 '24 08:08 CharlieZhuo