简体   繁体   English

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

[英]How to exclude test files in next.js during build?

I am creating next.js app with tests inside the page directory.我正在页面目录中创建带有测试的 next.js 应用程序。 For this I have added config to next.config.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;

All my pages have an extension page.tsx.我所有的页面都有扩展名 page.tsx。 For example Home.page.tsx.例如 Home.page.tsx。 My test files are named as follows: Home.spec.tsx.我的测试文件命名如下:Home.spec.tsx。

The problem is, my test files are still included in the build.问题是,我的测试文件仍然包含在构建中。 I did exclude them in my tsconfig file我确实在我的 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"]
}

I'm not sure what else I should do我不确定我还应该做什么

Do not put your test inside of the pages directory.不要将测试放在 pages 目录中。 If you do so, NextJS will consider this file to be a route of your application, and you will get an error like this when you try to build your app.如果你这样做了,NextJS 会认为这个文件是你的应用程序的一个路由,当你尝试构建你的应用程序时,你会得到这样的错误。

You can have your .spec files in any other folder such as /components but not /pages .您可以将.spec文件放在任何其他文件夹中,例如/components但不能放在/pages中。 As per documentation , for testing pages you will need to create a __test__ folder in the root.根据文档,对于测试页面,您需要在根目录中创建一个__test__文件夹。

Feel free afterwards to also update your exclude setting as:之后随意更新您的排除设置:

{
"exclude": ["node_modules"]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM