Questions & Answers

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

I am creating next.js app with tests inside the page directory. For this I have added config to next.config.js

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

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

module.exports = nextConfig;

All my pages have an extension page.tsx. For example My test files are named as follows: Home.spec.tsx.

The problem is, my test files are still included in the build. I did exclude them in my tsconfig file

    "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

2023-01-18 23:25:03
Can you share a bit more details. What is the structure of your pages directory?
Answers(1) :

Do not put your test inside of the pages directory. 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.

You can have your .spec files in any other folder such as /components but not /pages. As per documentation, for testing pages you will need to create a __test__ folder in the root.

Feel free afterwards to also update your exclude setting as:

"exclude": ["node_modules"]