How can you mock the internal fetch of your route handler? #1063
-
|
Hey there, thanks for such an amazing library. I'm having some issues trying to mock the response of a fetch used inside the route handler. Let's say I've a route handler like this (simplified for demo purposes): // [token]/route.js
export const GET = (request, { params }) => {
try {
if (!params.token) {
throw new Error('Missing token param');
}
// ↓ how can I mock this fetch?
const res = await fetch('https://api.example.com', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
token: params.token,
}),
});
const json = await data.json();
if (!json.session) {
throw new Error('No session available');
}
// success!
return NextResponse.redirect(new URL('/dashboard', request.url));
} catch (error) {
return NextResponse.redirect(new URL('/login', request.url));
}
}How can I mock the result of that fetch used inside my handler, so I can test different redirects? describe('setup link route handler', () => {
it('redirects to 404 if token param is missing', async () => {
await testApiHandler({
appHandler,
params: { token: '' },
async test({ fetch }) {
const res = await fetch({ method: 'GET' });
expect(res.status).toBe(307);
expect(res.headers.get('location')).toEndWith('/not-found');
},
});
});
it('redirects to 404 if token param is missing', async () => {
await testApiHandler({
appHandler,
params: { token: '12345' },
async test({ fetch }) {
const res = await fetch({ method: 'GET' });
expect(res.status).toBe(307);
expect(res.headers.get('location')).toEndWith('/not-found');
},
});
});
});I tried using msw to setup some mock results, but that does not seem to do anything, which I believe is due to how Next mocks the fetch globally. I would love some guidance as I've been knocking my head trying to test route handlers. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
Hey there! Unfortunately, it seems like you're running into the incompatibility between MSW and the Next.js App Router. It looks thorny, but there are some ways you can restore the Native/MSW fetch if you don't want to use Next's. |
Beta Was this translation helpful? Give feedback.
Hey there! Unfortunately, it seems like you're running into the incompatibility between MSW and the Next.js App Router. It looks thorny, but there are some ways you can restore the Native/MSW fetch if you don't want to use Next's.