如何手动初始化 next.js 应用程序(用于测试目的)?

pom*_*421 2 testing next.js

我尝试测试托管在 Next.js 应用程序中的 Web 服务,但出现错误,未找到 Next.js 配置。

我的网络服务是常规的,存储在pages/api目录中。ATTACKS_ENDPOINT由于这个文件,我的 API 测试获取了一个常量:

/pages/api/测试/api.spec.js

import { ATTACKS_ENDPOINT } from "../config"

...

describe("endpoints", () => {
   beforeAll(buildOptionsFetch)

   it("should return all attacks for attacks endpoint", async () => {
      const response = await fetch(API_URL + ATTACKS_ENDPOINT, headers)
Run Code Online (Sandbox Code Playgroud)

配置文件

import getConfig from "next/config"

const { publicRuntimeConfig } = getConfig()

export const API_URL = publicRuntimeConfig.API_URL
Run Code Online (Sandbox Code Playgroud)

我的 next.config.js 存在并且应用程序启动时可以正确使用。

当测试运行时,抛出此错误

    TypeError: Cannot destructure property `publicRuntimeConfig` of 'undefined' or 'null'.

  1 | import getConfig from "next/config"
  2 | 
> 3 | const { publicRuntimeConfig } = getConfig()
Run Code Online (Sandbox Code Playgroud)

我寻找解决方案,发现这个问题涉及_手动初始化__下一个应用程序。

鉴于我不测试 React 组件而是 API Web 服务,该怎么做?

maj*_*our 5

我通过创建一个jest.setup.js文件并添加这行代码解决了这个问题

首先将 jest.setup.js 添加到 jest.config.js 文件

// jest.config.js

module.exports = {
  // Your config
  setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
};
Run Code Online (Sandbox Code Playgroud)

进而

// jest.setup.js

jest.mock('next/config', () => () => ({
  publicRuntimeConfig: {
    YOUR_PUBLIC_VARIABLE: 'value-of-env'  // Change this line and copy your env
  }
}))
Run Code Online (Sandbox Code Playgroud)

或者

// jest.setup.js
import { setConfig } from 'next/config'
import config from './next.config'

// Make sure you can use "publicRuntimeConfig" within tests.
setConfig(config)
Run Code Online (Sandbox Code Playgroud)