Replies: 1 comment 15 replies
-
Hi, A bit late here, but here's a snippet I use here and there (it does create a dependency to a library called /**
* @jest-environment node
*/
import {NextURL} from 'next/dist/server/web/next-url';
// eslint-disable-next-line @next/next/no-server-import-in-page
import {NextRequest} from 'next/server'; // it's ok to import next/server here
import {instance, mock, reset, when} from 'ts-mockito';
const mockedRequest: NextRequest = mock(NextRequest);
afterEach(() => {
reset(mockedRequest);
});
// and then test
test('Rewrites from some-path to other-path', async () => {
const domain = 'https://example.com';
const url = new URL('/some-path', domain);
const nextUrl = new NextURL(url);
when(mockedRequest.nextUrl).thenReturn(nextUrl);
const result = await middleware(instance(mockedRequest));
expect(result).toBeDefined();
expect(result.status).toBe(200);
expect(result.headers.get('x-middleware-rewrite')).toBe(domain + '/other-path');
}); |
Beta Was this translation helpful? Give feedback.
15 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi!
I'm trying to going deep in new next middlewares.
Here a very dummy middleware:
I would like to test this middleware function via some unit tests via Jest.
Here the dummy example:
I'm going mad to understand how to provide all dependencies and let this test works.
Until now:
node/server
use exports syntax instead of module.exports like other modules. 💥BUT Request standard object is not defined in test environment:
ReferenceError: Request is not defined
... to be continued
Any suggestion how to create a valid Next Request or a valid mock to test the middleware?
PS: I know I can't move outside the logic and keep in that function just some returns, but for sake of knowledge I really want to test the middleware.
Beta Was this translation helpful? Give feedback.
All reactions