Skip to content
Discussion options

You must be logged in to vote

This is how I ended up testing my middleware:

import { middleware } from '../pages/_middleware';
import { NextResponse, NextRequest } from 'next/server';
import * as jose from 'jose';

describe('Middleware', () => {
  const redirectSpy = jest.spyOn(NextResponse, 'redirect');

  afterEach(() => {
    redirectSpy.mockReset();
  });

  it('should redirect to the homepage if visiting an admin page as a user without an auth token', async () => {
    const req = new NextRequest(new Request('https://www.whatever.com/admin/check-it-out'), {});
    req.headers.set(
      'cookie',
      'token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2NTg3NjczMjYsImV4cCI6…

Replies: 4 comments 9 replies

Comment options

You must be logged in to vote
9 replies
@derozn
Comment options

@jhancock532
Comment options

@vinicios-gomes
Comment options

@jhancock532
Comment options

@gflohr
Comment options

Answer selected by zeckdude
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet