Skip to content

Commit

Permalink
fix: tests, enforce unhandled mocked requests (#1713)
Browse files Browse the repository at this point in the history
  • Loading branch information
ivyjeong13 authored Feb 11, 2025
1 parent ab570f7 commit d21a00d
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
6 changes: 6 additions & 0 deletions ui/admin/test/mocks/handlers/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
mockedWorkspaceFilesToolReference,
} from "test/mocks/models/toolReferences";

import { OAuthApp } from "~/lib/model/oauthApps";
import { EntityList } from "~/lib/model/primitives";
import { ToolReference } from "~/lib/model/toolReferences";
import { ApiRoutes } from "~/lib/routers/apiRoutes";
Expand All @@ -33,4 +34,9 @@ export const toolsHandlers = [
items: mockedToolReferences,
});
}),
http.get(ApiRoutes.oauthApps.getOauthApps().path, () => {
return HttpResponse.json<EntityList<OAuthApp>>({
items: [],
});
}),
];
39 changes: 37 additions & 2 deletions ui/admin/test/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@ import "@testing-library/jest-dom";
import { mutate } from "swr";
import { server } from "test/server";

declare module "vitest" {
interface Assertion {
notToHaveUnhandledCalls(): void;
}
}

// for ThemeProvider, mock window.matchMedia
Object.defineProperty(window, "matchMedia", {
writable: true,
Expand All @@ -24,17 +30,46 @@ global.ResizeObserver = class ResizeObserver {
disconnect() {}
};

expect.extend({
notToHaveUnhandledCalls(received) {
const pass = received.mock.calls.length === 0;

if (!pass) {
const unhandledRequests = received.mock.calls
.map(([req]: [Request]) => `${req.method} ${req.url}`)
.join("\n ");

return {
pass,
message: () =>
`[MSW] Error: intercepted a request without a matching request handler:\n\n ${unhandledRequests}\n\n Make sure to add appropriate request handlers for these calls. \n Read more: https://mswjs.io/docs/getting-started/mocks`,
};
}
return { pass, message: () => "No unhandled calls detected" };
},
});

const onUnhandledRequest = vi.fn();

// Establish API mocking before all tests
beforeAll(() => server.listen());
beforeAll(() =>
server.listen({
onUnhandledRequest: onUnhandledRequest,
})
);

beforeEach(() => {
// Clear the SWR cache before each test
mutate(() => true, undefined, { revalidate: true });
onUnhandledRequest.mockClear();
});

// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => server.resetHandlers());
afterEach(() => {
server.resetHandlers();
expect(onUnhandledRequest).notToHaveUnhandledCalls();
});

// Clean up after the tests are finished.
afterAll(() => server.close());

0 comments on commit d21a00d

Please sign in to comment.