Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[docs] Env loading in a jest testing environment is too vague #26092

Closed
mattcarlotta opened this issue Jun 14, 2021 · 1 comment
Closed

[docs] Env loading in a jest testing environment is too vague #26092

mattcarlotta opened this issue Jun 14, 2021 · 1 comment
Labels
bug Issue was opened via the bug report template.

Comments

@mattcarlotta
Copy link
Contributor

mattcarlotta commented Jun 14, 2021

What version of Next.js are you using?

Latest

What version of Node.js are you using?

N/A

What browser are you using?

N/A

What operating system are you using?

N/A

How are you deploying your application?

N/A

Describe the Bug

The documentation assumes Jest will automatically execute an exported async function. However, this is not the case for files loaded through setupFiles/setupFilesAfterEnv.

Jest will execute function exports from globalSetup and globalTeardown; however setupFiles and setupFilesAfterEnv will not.

This can lead to confusion: #26005 on how to load Envs in a test environment.

This also leads to the next problem, currently Jest doesn't fully support ESM and therefore you have to use babel-jest and a custom babel configuration to transpile ESM to CommonJS: babeljs docs, CRA jest config and with-jest example. Otherwise, you'll run into this error:

Jest Error
Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

/home/m6d/Desktop/myapp/utils/loadConfig.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { loadConfig } from "@next/env";
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

Therefore the documentation, as described below, is too vague:

// The below can be used in a Jest global setup file or similar for your testing set-up
import { loadEnvConfig } from '@next/env'
export default async () => {  
 const projectDir = process.cwd()  
 loadEnvConfig(projectDir)
}

Reference to PR: #22982

Expected Behavior

Clear up the documentation by:

❶ Specifying that a custom babel configuration is required:
.babelrc

{  
  "presets": ["next/babel"] 
}

or

babel.config.js:

module.exports = (api) => {
  api.cache(() => process.env.NODE_ENV);

  return {
    presets: ["next/babel"],
  };
};

❷ Specifying which jest property should be to used to load Envs. Since there's no consensus, and loadConfig is not a Promise, I'd recommend setupFiles:
jest.config.js

module.exports = {
  "testEnvironment": "jsdom",
  "clearMocks": true,
  "moduleDirectories": ["<rootDir>", "node_modules"],
  "moduleNameMapper": {
    ".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/utils/fileMock.js",
    "\\.(css|scss)$": "identity-obj-proxy"
  },
  "transform": {
    "^.+\\.(ts|js)x?$": "babel-jest",
    ".+\\.(css|styl|less|sass|scss)$": "jest-css-modules-transform"
  },
  "testPathIgnorePatterns": [
    "<rootDir>/.next",
    "<rootDir>/coverage",
    "<rootDir>/node_modules",
    "<rootDir>/public",
    "<rootDir>/babel.config.js",
    "<rootDir>/next.config.js"
  ],
  "collectCoverageFrom": ["**/*.{js,jsx}"],
  "coveragePathIgnorePatterns": ["<rootDir>/pages"],
  "setupFiles": ["<rootDir>/utils/loadEnv.js"],
}

❸ Updating the documentation code to simply import and invoke the loadConfig function:
utils/loadEnv.js

import { loadConfig } from "@next/env"

loadConfig(process.cwd())

Alternatively, avoid all of the above, update the with-jest example to include environment loading and replace the documentation code with a simple link to the with-jest example:

Examples

To Reproduce

N/A

@mattcarlotta mattcarlotta added the bug Issue was opened via the bug report template. label Jun 14, 2021
@balazsorban44
Copy link
Member

This issue has been automatically locked due to no recent activity. If you are running into a similar issue, please create a new issue with the steps to reproduce. Thank you.

@vercel vercel locked as resolved and limited conversation to collaborators Jan 28, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
bug Issue was opened via the bug report template.
Projects
None yet
Development

No branches or pull requests

2 participants