I’m working on a small personal project that is built on NextJs V14, I am starting to write tests around some of the components but I’m running into some difficulty when the component I’m testing is using my authentication solution. Any tests around code which touches ‘auth.ts’ fails with this error:
import { Auth } from “@auth/core”; SyntaxError: Cannot use import
statement outside a module`
This is how I’ve set my project up:
auth.ts:
import NextAuth from "next-auth"
import authConfig from "./auth.config";
export const { handlers, signIn, signOut, auth } = NextAuth({
...authConfig
})
page.tsx (directed to this on signin):
import Loading from "@/components/loading/loading";
import styles from './signedIn.module.css';
import { auth } from "@/auth";
import { createAccount, getUserAppAccount, getUserProjects } from "@/lib/db";
import { AppAccount, Project } from "@/lib/definitions";
import { redirect } from "next/navigation";
export default async function SignedIn(){
const session = await auth();
if(!session?.user?.id){
//to-do: redirect to error page.
return
}
const appAccount = await getUserAppAccount(session?.user?.id) as AppAccount;
if(appAccount){
const projects = await getUserProjects(appAccount) as Project[];
if(projects.length <= 0){
redirect('/onboard');
}
redirect(`/project/${projects[0]?._id?.toString()}/task-board`);
} else {
redirect('/onboard');
}
return (
<div className={styles.view}>
<Loading />
</div>
);
}
page.test.tsx
// __tests__/SignedIn.test.js
import { render, screen, waitFor } from '@testing-library/react';
import '@testing-library/jest-dom';
import SignedIn from '@/app/signed-in/page'; // Adjust the path as necessary
import * as authO from "@/auth";
import { useRouter } from 'next/router';
import {jest} from '@jest/globals';
describe('SignedIn Component', () => {
test('redirects to error page if no session', async () => {
jest.spyOn(authO, "auth").mockResolvedValue(null as never);
render(<SignedIn />);
});
});
jest.config.ts
import type { Config } from 'jest'
import nextJest from 'next/jest.js'
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
moduleNameMapper: {
'react-markdown': require.resolve('react-markdown'),
'rehypeRaw': require.resolve('rehype-raw'),
'^@/auth': '<rootDir>/src/auth.ts',
},
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
export default createJestConfig(config)
I’ve tried mocking NextAuth, but I got the same error. I also tried setting up babel. But nothing really worked, I don’t think that was the correct route to go down. I’ve looked high and low for similar issues but nothing I have found has been applicable. ChatGPT had me going in circles…
Rorry KElly is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.