vite-test-utils
vite-test-utils copied to clipboard
Cant get setup({server: true}) to work
Describe the bug
I try to test an endpoint of my sveltekit app that is redirecting a request to another domain. it goes like this:
import { redirect } from '@sveltejs/kit';
/** @type {import('@sveltejs/kit').Handle} */
export async function handle({ event, resolve }) {
const url = new URL(event.request.url);
url.host = 'toto.li';
url.port = '';
url.protocol = 'https';
console.log(`Redirecting to: ${url}`)
throw redirect(301, url);
}
My vitest is the following:
import { describe, it, expect, afterAll, beforeAll } from 'vitest';
import { setupServer } from 'msw/node'
import { rest } from 'msw'
import { setup } from 'vite-test-utils';
import fetch from 'node-fetch';
const mswServer = setupServer(
// catch the redirect and return the user agent of the request
rest.get('https://toto.li/123', (req, res, ctx) => {
return res(ctx.status(200), ctx.json({ id: req.headers.get('user-agent') }))
})
)
beforeAll(async () => {
mswServer.listen({ onUnhandledRequest: 'bypass' })
});
afterAll(() => mswServer.close())
describe('Test redirections', async () => {
await setup({ server: true }); // launch the application
it('should redirect directly when not request by a browser', async () => {
// request any endpoint, this will be handled in the hooks.server.js handler of sveltekit
const response = await fetch('http://localhost:3000/123', {
headers: {
'user-agent': 'whatever but not mozilla'
}
})
expect(response.status).toBe(200)
const data = await response.json()
// the msw mock for toto.li is returning the user-agent
expect(data.id).toBe('whatever but not mozilla')
})
});
With this, it seems that the mswServer mockup is failing to catch the request to toto.li that is executed in hooks.server.js.
If I remove the await setup({ server: true }) and manually launch the sveltekit app using npm run dev, everything is working fine.
Maybe it's a problem with msw but I thought I'd ask here first. What do you think?
Reproduction
see the description
System Info
System:
OS: Linux 5.10 Ubuntu 20.04.6 LTS (Focal Fossa)
CPU: (8) x64 Intel(R) Core(TM) i7-10610U CPU @ 1.80GHz
Memory: 22.24 GB / 24.74 GB
Container: Yes
Shell: 5.0.17 - /bin/bash
Binaries:
Node: 18.17.1 - ~/.nvm/versions/node/v18.17.1/bin/node
Yarn: 1.22.19 - /usr/bin/yarn
npm: 10.1.0 - ~/.nvm/versions/node/v18.17.1/bin/npm
Used Package Manager
npm
Additional context
No response
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guide.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Check that this is a concrete bug. For Q&A, please open a GitHub Discussion instead.
- [X] The provided reproduction is a minimal reproducible of the bug.