Repository navigation
Updating msw to v3, tests now fail because of missing matching OPTIONS request handler #2817
|
My test suite is vitest running client-side React JS/Typescript. Under v2, unit tests that made calls to external APIs would be handled instead by The corresponding document and the change log don't tell me what I need to do to handle OPTIONS now. Additionally, this is not really a warning as it throws an error, causing the unit tests to fail entirely (it never skips pass the failed OPTIONS request and never makes the corresponding GET requests that it's supposed to). |
Replies: 2 comments 3 replies
|
That Why it started with v3 MSW 3 moved from patching Fix (recommended): make the requests same-origin Set the test document URL to the origin your API calls use, or use relative URLs in tests: // vitest.config.ts
export default defineConfig({
test: {
environment: 'jsdom',
environmentOptions: {
jsdom: { url: 'http://localhost:8081' }, // your API origin
},
},
})On happy-dom you can turn off its same-origin check instead: environmentOptions: {
happyDOM: {
settings: { fetch: { disableSameOriginPolicy: true } },
},
},( If your API really is on another origin Add CORS headers to the mocked responses, and handle the preflight if one is sent: http.options('*', () =>
new HttpResponse(null, {
status: 204,
headers: {
'access-control-allow-origin': '*',
'access-control-allow-headers': '*',
},
}),
),
http.get('https://api.example.com/items', () =>
HttpResponse.json(fixture, {
headers: { 'access-control-allow-origin': '*' },
}),
),jsdom decides on its own when to send a preflight (custom headers trigger one, for example), so I'd treat this as a fallback. Aligning the origin is less work. One more v3 change to check: |
|
Hi. This is an intended behavior. v3.0 intercepts more of the underlying traffic, which now includes preflight requests if your environment makes those, which you have to handle as any other request. See more context here. This page also includes the common strategies for handling the I'm working on adding this to the docs somewhere to make this apparent. The migration guidelines for 3.0 sound like a good place to include this. |
Hi. This is an intended behavior. v3.0 intercepts more of the underlying traffic, which now includes preflight requests if your environment makes those, which you have to handle as any other request. See more context here. This page also includes the common strategies for handling the
OPTIONSrequests, which doesn't always mean creating handlers for them.I'm working on adding this to the docs somewhere to make this apparent. The migration guidelines for 3.0 sound like a good place to include this.