Build error occurred ReferenceError: describe is not defined > During now.sh deployment
Asked Answered
H

5

11

I'm using now.sh to deploy my nextjs (React) app. And the build is failing due to this error:

Build error occurred ReferenceError: describe is not defined

Not sure why this started happening, here is my .babelrc

{
  "env": {
    "development": {
      "compact": false,
      "presets": [
        "next/babel",
        "@zeit/next-typescript/babel"
      ],
      "plugins": [
        ["styled-components", {"ssr": true, "displayName": true}],
        ["@babel/plugin-proposal-decorators", {"legacy": true}]
      ]
    },
    "production": {
      "presets": [
        "next/babel",
        "@zeit/next-typescript/babel"
      ],
      "plugins": [
        ["styled-components", {"ssr": true, "displayName": true}],
        ["@babel/plugin-proposal-decorators", {"legacy": true}]
      ]
    },
    "test": {
      "compact": false,
      "presets": [
        "@babel/preset-typescript",
        ["next/babel", {"preset-env": { "modules": "commonjs" }}]
      ],
      "plugins": [
        ["styled-components", { "ssr": true, "displayName": true }],
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["babel-plugin-sass-vars"]
      ]
    }
  }
}

package.json

"engines" : { 
    "node" : ">=8.10.0 <11.0.0" 
  },
  "scripts": {
    "dev": "NODE_ENV=development next -p 7777",
    "build": "NODE_ENV=production next build",
    "start": "next -p 7777",
    "test": "NODE_ENV=test jest --no-cache",
    "test-watch": "NODE_ENV=test jest --watch --no-cache",
    "coverage": "NODE_ENV=test jest --coverage",
    "update-snap": "NODE_ENV=test jest --updateSnapshot"
  },

Full log:

running "npm run now-build"
> [email protected] now-build /tmp/7418164
> next build
Creating an optimized production build ...
> Using external babel configuration
> Location: "/tmp/7418164/.babelrc"
> Build error occurred
ReferenceError: describe is not defined
    at Module.kAI8 (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:63996:1)
    at __webpack_require__ (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:23:31)
    at module.exports.+3sd.exports.__esModule (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:91:18)
    at Object.<anonymous> (/tmp/7418164/.next/serverless/pages/__tests__/about.test.js:94:10)
    at Module._compile (module.js:652:30)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
npm
ERR! code ELIFECYCLE

The first test where the describe is used:

import React from 'react'
import { shallow } from 'enzyme'
import toJson from 'enzyme-to-json'

import About from '../about.tsx'

describe('<About /> component', () => {
  describe('rendering', () => {
    const wrapper = shallow(<About />);
    it('should render a component matching the snapshot', () => {
      const tree = toJson(wrapper);
      expect(tree).toMatchSnapshot();
      expect(wrapper).toHaveLength(1);
      expect(wrapper.contains(<About/>));
    });
  });
});

next.config

module.exports = (phase, { defaultConfig }) => {
  webpack: (config, { buildId, dev, isServer, defaultLoaders, webpack }) => {
    module: {
      loaders: [
        {
          test: /\.json$/,
          loader: 'json-loader'
        }
      ]
    }
    // Note: Nextjs provides webpack above so you should not `require` it
    // Perform customizations to webpack config
    // Important: return the modified config
    config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
    return config
  }

  // ✅ Put the require call here.
  const withTypescript = require('@zeit/next-typescript')
  const withCSS = require('@zeit/next-sass')

  // withCSS({target: 'serverless'})
  return withTypescript(withCSS({
    webpack(config, options) {
      return config
    }
  }))
}
Homburg answered 8/9, 2019 at 3:7 Comment(8)
In your last piece of code, where are you declaring describe?Galang
Well describe is part of jest. I've never had to declare describe before in any app :(Homburg
Whoa strange, I just commented out the about.test.js code and it deployed fine ?? :( and I have other tests that also use describe so strange...Homburg
@LeonGaban how does your next.config.js look like (you can just post related code)Fortunato
@Fortunato just added my next.config!Homburg
@LeonGaban was this line added before the fix config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//)) or is that the fix that run your build successfullyFortunato
@Fortunato ah I don't recall now... I just don't test the pages directory, are you able to in your NextJS app?Homburg
Just don't put any test files in the pages folder, because Next.js treats all files for routing which are in the pages folder.Vey
H
20

I removed the tests that covered the /pages directory. NextJS used pages for routing. Not sure why that was causing the problem, ran coverage and looks like pages wasn't necessary to cover.

Hoping for a better answer from someone at the NextJS / Now.sh team, and I'll select that.

Homburg answered 8/9, 2019 at 3:24 Comment(3)
By default Next.js tries to treat all files in the /pages directory as pages for routing. You can customize the file extension of pages with nextjs.org/docs/api-reference/next.config.js/… so it will ignore files without that file extension. See my answer below https://mcmap.net/q/960871/-build-error-occurred-referenceerror-describe-is-not-defined-gt-during-now-sh-deployment.Teratology
it works! You need move files.test.js outside of pages directoryPuga
Works. Move your page tests to __tests__ folder.Meda
G
5

Easy fix: https://github.com/zeit/next.js/issues/3728#issuecomment-523789071

pageExtensions: ['page.tsx']
Gallman answered 7/2, 2020 at 10:18 Comment(1)
Worked for me, as I had some .test.ts files on the /pages folder.Sanalda
T
4

Edit: This answer is no longer needed for the new Next.js v13 app router which allows colocating other files with your pages in the /app directory.

If you are looking to colocate non-page files with pages in the /pages directory, you can use Custom Page Extensions to force your pages to have a file extension of .page.js. Once that is setup, Next.js will ignore any files that don't have .page in the file extension.

next.config.js

module.exports = {
  // Force .page prefix on page files (ex. index.page.tsx) so generated files can be included in /pages directory without Next.js throwing build errors
  pageExtensions: ['page.tsx', 'page.ts', 'page.jsx', 'page.js'],
}

I wrote some docs for this use case that have yet to be merged https://github.com/vercel/next.js/pull/22740. The docs link above now contains these changes.

The original Github issue where this was discovered is https://github.com/vercel/next.js/issues/3728#issuecomment-895568757.

Be aware that with the new Next.js v13 app router, this is no longer necessary as you can colocate other files with your pages in the router /app directory. If you've customized pageExtensions, this config will also apply to the app router and force you to rename pages in /app also. See https://github.com/vercel/next.js/issues/51478#issuecomment-1672314182 for more details about how pageExtensions affects the new app router file naming.

Teratology answered 9/8, 2021 at 21:51 Comment(0)
J
2

An option that allows the tests inside pages folder:

change webpack settings direct in next.config.js

module.exports = {
  webpack: (config, { webpack }) => {
    config.plugins.push(new webpack.IgnorePlugin(/\/__tests__\//))
    return config
  }
}

It is ignoring whatever __tests__ folder found on the build process.

Juback answered 16/4, 2020 at 12:54 Comment(1)
This no longer works for Next.js 11 Error: Build optimization failed: found pages without a React Component as default export.Abbevillian
E
1

I had to add page to my file extensions and add pageExtensions property to nextjs config:

import os
import subprocess

# Function to rename files
def rename_files():
    # Iterate over all files in the directory and subdirectories
    result = subprocess.run(
        ["find", "src/pages/", "-type", "f"], 
        stdout=subprocess.PIPE, 
        text=True
    )

    # Split the output into a list of file paths
    files = result.stdout.strip().split('\n')
    #print(files)
    extensions = set()
    for file in files:
        # Check if the file name does not contain the word "test"
        if "test" not in file.lower():
            # Get the file's current extension
            name, ext = os.path.splitext(file)
            extensions.add(ext)
            
            # Create the new file name with the updated extension
            new_name = f"{name}.page{ext}"
            
            print(f"{file} -> {new_name}")
            
            # Rename the file
            subprocess.run(["git", "mv", file , new_name], check=True)
            #print(f"Renamed: {old_path} -> {new_path}")
    print(f"unique extensions:\n{extensions}")

rename_files()

diff --git a/next.config.js b/next.config.js
index 19e9e913..d1b2ad18 100644
--- a/next.config.js
+++ b/next.config.js
@@ -30,7 +30,8 @@ const moduleExports = {
     },
     images: {
         domains: ['https://www.tailwindui.com', 'https://app.myapp.com', 'https://www.myapp.com', 'tailwindui.com']
-    }
+    },
+    pageExtensions: ['page.js', 'page.ts', 'page.tsx']
};

 module.exports = moduleExports;
\ No newline at end of file

https://github.com/vercel/next.js/discussions/34249

https://nextjs.org/docs/pages/api-reference/next-config-js/pageExtensions#including-non-page-files-in-the-pages-directory

I'm on nextjs 13.5.1

Encomium answered 14/8 at 2:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.