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

Next.js 13组件使用next/headers时Jest测试失败求助

解决Next.js 13中next/headers在Jest测试中的报错问题

问题描述

使用Next.js 13开发组件时,引入next/headers中的cookies后,运行Jest测试抛出NEXT_RSC_ERR_CLIENT_IMPORT错误,手动mock该模块无效。

组件代码

import { cookies } from 'next/headers';

function Simple() {
  console.log({ cookies });
  return <div>Simple</div>;
}

export default Simple;

测试代码

import { render } from '@testing-library/react';

import Simple from './Simple';

describe('<Simple />', () => {
  it('should render Simple component', () => {
    render(<Simple />);
  });
});

报错信息

x NEXT_RSC_ERR_CLIENT_IMPORT: next/headers
       ,-[1:1]
     1 | import { cookies } from 'next/headers';
       : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
     2 | 
     3 | function Simple() {
     4 |   console.log({ cookies });

当前配置

jest.config.js:

const nextJest = require('next/jest');

const createJestConfig = nextJest({
  dir: './',
});

const customJestConfig = {
  setupFilesAfterEnv: ['./.jest/setup.js'],
  testEnvironment: 'jest-environment-jsdom',
};

module.exports = async () => ({
  ...(await createJestConfig(customJestConfig)()),
});

./jest/setup.js:

require('jest-fetch-mock').enableMocks();

import '@testing-library/jest-dom';

相关包版本

"next": "13.1.0",
    "jest": "^29.3.1",
    "jest-environment-jsdom": "^29.3.1",
    "jest-fetch-mock": "^3.0.3",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",

解决方案

1. 修正next/headers的Mock逻辑

next/headers是Next.js服务器组件专属API,客户端测试环境无法直接运行。需要正确mockcookies的导出形式——它是一个函数,调用后返回包含操作方法的对象。修改测试文件如下:

import { render } from '@testing-library/react';
import Simple from './Simple';

// 正确mock next/headers模块
jest.mock('next/headers', () => ({
  cookies: jest.fn(() => ({
    // 模拟业务中用到的cookies方法,比如get
    get: jest.fn((name) => {
      // 可根据测试需求返回对应mock值
      if (name === 'user_id') return 'mock_user_123';
      return null;
    }),
    // 其他需要的方法(如getAll、set)可按需添加
  })),
}));

describe('<Simple />', () => {
  it('should render Simple component', () => {
    render(<Simple />);
  });
});

2. 架构层面优化(可选)

如果该组件是客户端组件(未添加'use server'指令),建议避免直接在组件中使用next/headers:

  • 改为在服务器组件中获取cookie值,通过props传递给客户端组件
  • 或使用Server Actions封装cookie操作逻辑,客户端组件调用action获取数据

这种方式更符合Next.js的RSC架构设计,从根源上避免测试环境的API兼容性问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 00:10:20