How to setup MSW for Vitest browser mode? #2303
-
I'm trying Vitest browser mode (still experimental) and I'm wondering what's the canonical way to setup MSW in this mode? I tried: // src/vitest-setup.ts
import { worker } from "./mocks/browser";
import { cleanup } from "@testing-library/react";
// from https://mswjs.io/docs/getting-started/integrate/node#setup
// Establish API mocking before all tests.
beforeAll(async () => {
await worker.start({ onUnhandledRequest: "error" });
});
// Reset any request handlers that we may add during the tests,
// so they don't affect other tests.
afterEach(() => {
worker.resetHandlers();
cleanup();
});
// Clean up after the tests are finished.
afterAll(() => {
worker.stop();
}); with: // vitest.config.ts
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
setupFiles: ["src/vitest-setup.ts"],
globals: true,
browser: {
enabled: true,
name: "chromium",
provider: "playwright",
},
},
}); While this seems to work, I'm not sure this is 100% correct. Also, I am not able to override a request in a single test using: worker.use(...);
render(<MyComponent />); The override doesn't seem to have any effect or to be taken into account. EDIT: the override works if I move whatever I have inside |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Hi, @foxaltus. I suspect that setup files aren't applied in the browser. That's still the setup file for your Node.js run of Vitest. @sheremet-va, please correct me if I'm wrong. |
Beta Was this translation helpful? Give feedback.
-
I've added the Vitest Browser Mode recipe to the MSW docs. Please follow it to integrate MSW with Vitest Browser Mode. Thanks! |
Beta Was this translation helpful? Give feedback.
I've added the Vitest Browser Mode recipe to the MSW docs. Please follow it to integrate MSW with Vitest Browser Mode. Thanks!