Atinux / nuxt-auth-utils

Minimal Auth module for Nuxt 3.
MIT License
593 stars 57 forks source link

How to write a unit test for nuxt middleware? #96

Open ilrein opened 3 weeks ago

ilrein commented 3 weeks ago

Given this code example:

export default defineNuxtRouteMiddleware(() => {
  const { loggedIn } = useUserSession()

  if (!loggedIn.value) {
    return navigateTo('/')
  }
})

Could I please get some help writing a unit test for this (the goal is to mock useUserSession)?

I roughly tried something like this:

import { describe, it, expect, vi } from 'vitest';
// import { defineNuxtRouteMiddleware, navigateTo } from '#app';
// Import the middleware
import authMiddleware from '~/middleware/auth';

// Mock useUserSession composable
// vi.mock('nuxt-auth-utils', () => ({
//   useUserSession: vi.fn(),
// }));
// vi.mock('useUserSession', () => ({
//   loggedIn: { value: false },
// }));

// Mock navigateTo function
// vi.mock('#app', () => ({
//   navigateTo: vi.fn(),
// }));

describe('auth middleware', () => {
  const to = { path: '/some-path' };  // Mock destination route
  const from = { path: '/another-path' };  // Mock current route

  it('redirects to home page if user is not logged in', async () => {
    // const { useUserSession } = useNuxtApp()
    // Mock the user session to be logged out
    // const { useUserSession } = require('nuxt-auth-utils');
    // useUserSession.mockReturnValue({ loggedIn: { value: false } });

    // Execute the middleware function
    const result = authMiddleware(to, from);

    // Verify if navigateTo was called with '/'
    expect(navigateTo).toHaveBeenCalledWith('/');
  });

  // it('does not redirect if user is logged in', async () => {
  //   // Mock the user session to be logged in
  //   // const { useUserSession } = require('nuxt-auth-utils');
  //   useUserSession.mockReturnValue({ loggedIn: { value: true } });

  //   // Execute the middleware function
  //   const result = authMiddleware(to, from);

  //   // Verify if navigateTo was not called
  //   expect(navigateTo).not.toHaveBeenCalled();
  // });
});

But can't quite get the result I want. Any help would be great!

rahulkumarsingh73690 commented 1 week ago

+1