如何在构建过程中排除 next.js 中的测试文件?

Vyt*_*vys 11 typescript reactjs webpack jestjs next.js

我正在创建 next.js 应用程序,并在页面目录中进行测试。为此,我已将配置添加到 next.config.js

const { i18n } = require('./next-i18next.config');

const nextConfig = {
    reactStrictMode: true,
    pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
    styledComponents: true,
    i18n,
};

module.exports = nextConfig;

Run Code Online (Sandbox Code Playgroud)

我的所有页面都有一个扩展名 page.tsx。例如 Home.page.tsx。我的测试文件命名如下:Home.spec.tsx。

问题是,我的测试文件仍然包含在构建中。我确实将它们排除在我的 tsconfig 文件中

{
    "compilerOptions": {
        "target": "es5",
        "lib": ["dom", "dom.iterable", "esnext"],
        "allowJs": true,
        "skipLibCheck": true,
        "strict": true,
        "forceConsistentCasingInFileNames": true,
        "noEmit": true,
        "esModuleInterop": true,
        "module": "esnext",
        "moduleResolution": "node",
        "resolveJsonModule": true,
        "isolatedModules": true,
        "jsx": "preserve",
        "incremental": true,
        "types": ["node", "jest", "@testing-library/jest-dom"]
    },
    "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
    "exclude": ["node_modules", "**/*.spec.ts", "**/*.spec.tsx"]
}
Run Code Online (Sandbox Code Playgroud)

我不知道我还应该做什么

use*_*488 10

不要将测试放在页面目录中。如果你这样做,NextJS 会认为这个文件是你的应用程序的路径,当你尝试构建你的应用程序时,你会收到这样的错误。

您可以将.spec文件放在任何其他文件夹中,例如/components但不可以/pages。根据文档,为了测试页面,您需要__test__在根目录中创建一个文件夹。

之后也可以将您的排除设置更新为:

{
"exclude": ["node_modules"]
}
Run Code Online (Sandbox Code Playgroud)