You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js 14中Jest测试Next-Auth时遇模块导入语法错误

Next.js 14项目Jest测试认证组件时出现@auth/core模块导入错误

问题描述

开发基于Next.js 14的个人项目时,编写涉及认证逻辑的组件测试时触发错误:

import { Auth } from "@auth/core"; SyntaxError: Cannot use import statement outside a module

相关代码配置

auth.ts

import NextAuth from "next-auth"
import authConfig from "./auth.config";
 
export const { handlers, signIn, signOut, auth } = NextAuth({
    ...authConfig
})

登录跳转页面 page.tsx

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)

已尝试的解决方案

  • 模拟NextAuth模块,但错误依旧
  • 配置Babel,无效果
  • 查阅大量同类问题及ChatGPT方案,均无法解决

内容的提问来源于stack exchange,提问作者Rorry KElly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 17:12:49