Home > Net >  How do I write tests for pages middleware (Next 12)?
How do I write tests for pages middleware (Next 12)?

Time:07-26

I have added some logic in my pages middleware (using Next 12) and would like to add tests now but am pretty lost on how to get that started. Can someone direct me to a tutorial or resource that shows a complete example of middleware being tested?

Specifically this is what my middleware is doing:

export function middleware(request: NextRequest) {
  // Redirect a user if they don't have an auth token and are not the admin role 
  if (request.nextUrl.pathname.startsWith('/admin')) {
    const authTokenCookie = request.cookies.token;
    const parsedToken = authTokenCookie ? jose.decodeJwt(authTokenCookie) : null;
    const role = typeof parsedToken === 'object' ? parsedToken?.role : null;

    if (!authTokenCookie || !role || role !== USER_ROLES.admin) {
      return NextResponse.redirect(new URL('/', request.url));
    }
  }

  // Redirect the user if a query parameter is present
  if (request.nextUrl.pathname === '/' && request.nextUrl.searchParams.has('directToStore')) {
    NextResponse.redirect(new URL('/store', request.url));
  }

  return NextResponse.next();
}

CodePudding user response:

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.eyJpc3MiOiJPbmxpbmUgSldUIEJ1aWxkZXIiLCJpYXQiOjE2NTg3NjczMjYsImV4cCI6MTY5MDMwMzMyNiwiYXVkIjoid3d3LmV4YW1wbGUuY29tIiwic3ViIjoianJvY2tldEBleGFtcGxlLmNvbSIsInJvbGUiOiJ1c2VyIn0.G7rkptAKt1icBp92KcHYpGdcWOnn4gO8vWiCMtIHc0c;',
    );
    const { role } = jose.decodeJwt(req.cookies.token);

    await middleware(req);

    expect(role).toEqual('user');
    expect(redirectSpy).toHaveBeenCalledTimes(1);
    expect(redirectSpy).toHaveBeenCalledWith(new URL('/', req.url));
  });

  it('should redirect to the store if the directToStore query param is set', async () => {
    const req = new NextRequest(new Request('https://www.whatever.com'), {});
    req.nextUrl.searchParams.set('directToStore', 'true');

    await middleware(req);

    expect(redirectSpy).toHaveBeenCalledTimes(1);
    expect(redirectSpy).toHaveBeenCalledWith(new URL('/store', req.url));
  });
});
  • Related