Unverified Commit 4a14671f authored by Damien Simonin Feugas's avatar Damien Simonin Feugas Committed by GitHub

fix(next/jest): jest can not load server-only code (#52393)

### 🧐 What's in there?

At the moment, it is not possible to test code with `import 'server-only'` in app directory.
When trying to load such file in jest (even with `testEnvironment: node`), the error will be:
```
      ● Test suite failed to run··
          x NEXT_RSC_ERR_CLIENT_IMPORT: server-only
           ,-[lib/util.js:1:1]
         1 | /** @jest-environment node */·
         2 |         import 'server-only'
           :         ^^^^^^^^^^^^^^^^^^^^
         3 |         export const PI = 3.14;
           `----·
          at Object.transformSync (node_modules/next/src/build/swc/index.ts:443:25)
          at transformSync (node_modules/next/src/build/swc/index.ts:629:19)
          at Object.process (node_modules/next/src/build/swc/jest-transformer.ts:117:25)
          at ScriptTransformer.transformSource (node_modules/@jest/transform/build/ScriptTransformer.js:619:31)
          at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:765:40)
          at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:822:19)·
```

In a nutshell:
- next/swc is looking for ‘server-only’ [text in the source](https://github.com/vercel/next.js/blob/canary/packages/next-swc/crates/core/src/react_server_components.rs#L576), and throw if not configured for server
- next's jest-transformer will only configure next/swc for server [if the environment is node](https://github.com/vercel/next.js/blob/canary/packages/next/src/build/swc/jest-transformer.ts#L88)
- when testing Next.js apps, your jest testEnvironment is most likely jsdom. But you can configure it [per file with docBlock](https://jestjs.io/docs/configuration#testenvironment-string), which jest-transformer ignores because it only reads the top-level configuration.

This PR fixes this, by 
1. reading the docblock to configure next/swc accordingly and bypass its hardcoded guard
2. mocking `server-only` so [it does not throw](https://github.com/vercel/next.js/blob/canary/packages/next/src/compiled/server-only/index.js) when loaded (jest does not read `react-server` export from package.json)

Users would still have to annotate their `server-only` files with `/** @jest-environment node */` in order to test them.

### 🧪 How to test?

There's a full test available: `pnpm testheadless --testPathPattern jest/server-only`

Here is also a minimal reproduction:

<details>
    <summary>app/layout.tsx</summary>

```typescript
export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (<html lang="en"><body>{children}</body></html>)
}
```
</details>

<details>
    <summary>app/page.tsx</summary>

```typescript
import { PI } from '@/lib/utils'

export default function Home() {
    return <h1>{PI}</h1>
}
```
</details>

<details>
    <summary>lib/utils.ts</summary>

```typescript
import 'server-only'

export const PI = 3.14
```
</details>

<details>
    <summary>lib/utils.test.ts</summary>

```typescript
import { PI } from './utils'

it('works', () => expect(PI).toEqual(3.14))
```
</details>

<details>
    <summary>jest.config.js</summary>

```typescript
const nextJest = require('next/jest')

module.exports = nextJest({ dir: './' })({ testEnvironment: 'jsdom' })
```
</details>

### ❗ Notes to reviewers

[jest-docblock](https://packagephobia.com/result?p=jest-docblock) with dependencies is only 12.5 kB.


Fixes #47448
parent 2441ad47
...@@ -239,6 +239,7 @@ ...@@ -239,6 +239,7 @@
"image-size": "1.0.0", "image-size": "1.0.0",
"is-docker": "2.0.0", "is-docker": "2.0.0",
"is-wsl": "2.2.0", "is-wsl": "2.2.0",
"jest-docblock": "29.4.3",
"jest-worker": "27.0.0-next.5", "jest-worker": "27.0.0-next.5",
"json5": "2.2.3", "json5": "2.2.3",
"jsonwebtoken": "9.0.0", "jsonwebtoken": "9.0.0",
......
// this empty files is only here to mock server-only imports
...@@ -137,6 +137,8 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -137,6 +137,8 @@ export default function nextJest(options: { dir?: string } = {}) {
'@next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'), '@next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'),
// Handle next/font // Handle next/font
'next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'), 'next/font/(.*)': require.resolve('./__mocks__/nextFontMock.js'),
// Disable server-only
'server-only': require.resolve('./__mocks__/empty.js'),
// custom config comes last to ensure the above rules are matched, // custom config comes last to ensure the above rules are matched,
// fixes the case where @pages/(.*) -> src/pages/$! doesn't break // fixes the case where @pages/(.*) -> src/pages/$! doesn't break
......
...@@ -29,6 +29,7 @@ DEALINGS IN THE SOFTWARE. ...@@ -29,6 +29,7 @@ DEALINGS IN THE SOFTWARE.
import vm from 'vm' import vm from 'vm'
import { transformSync } from './index' import { transformSync } from './index'
import { getJestSWCOptions } from './options' import { getJestSWCOptions } from './options'
import * as docblock from 'next/dist/compiled/jest-docblock'
import type { import type {
TransformerCreator, TransformerCreator,
TransformOptions, TransformOptions,
...@@ -76,16 +77,30 @@ function isEsm( ...@@ -76,16 +77,30 @@ function isEsm(
) )
} }
function getTestEnvironment(
src: string,
jestConfig: Config.ProjectConfig
): string {
const docblockPragmas = docblock.parse(docblock.extract(src))
const pragma = docblockPragmas['jest-environment']
const environment =
(Array.isArray(pragma) ? pragma[0] : pragma) ?? jestConfig.testEnvironment
return environment
}
const createTransformer: TransformerCreator< const createTransformer: TransformerCreator<
SyncTransformer<JestTransformerConfig>, SyncTransformer<JestTransformerConfig>,
JestTransformerConfig JestTransformerConfig
> = (inputOptions) => ({ > = (inputOptions) => ({
process(src, filename, jestOptions) { process(src, filename, jestOptions) {
const jestConfig = getJestConfig(jestOptions) const jestConfig = getJestConfig(jestOptions)
const testEnvironment = getTestEnvironment(src, jestConfig)
const swcTransformOpts = getJestSWCOptions({ const swcTransformOpts = getJestSWCOptions({
// When target is node it's similar to the server option set in SWC. // When target is node it's similar to the server option set in SWC.
isServer: jestConfig.testEnvironment === 'node', isServer:
testEnvironment === 'node' ||
testEnvironment.includes('jest-environment-node'),
filename, filename,
jsConfig: inputOptions?.jsConfig, jsConfig: inputOptions?.jsConfig,
resolvedBaseUrl: inputOptions?.resolvedBaseUrl, resolvedBaseUrl: inputOptions?.resolvedBaseUrl,
......
...@@ -251,6 +251,7 @@ export function getJestSWCOptions({ ...@@ -251,6 +251,7 @@ export function getJestSWCOptions({
jsConfig, jsConfig,
hasServerComponents, hasServerComponents,
resolvedBaseUrl, resolvedBaseUrl,
isServerLayer: isServer,
}) })
const isNextDist = nextDistPath.test(filename) const isNextDist = nextDistPath.test(filename)
......
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
(()=>{"use strict";var e={381:e=>{const detectNewline=e=>{if(typeof e!=="string"){throw new TypeError("Expected a string")}const t=e.match(/(?:\r?\n)/g)||[];if(t.length===0){return}const r=t.filter((e=>e==="\r\n")).length;const n=t.length-r;return r>n?"\r\n":"\n"};e.exports=detectNewline;e.exports.graceful=e=>typeof e==="string"&&detectNewline(e)||"\n"},37:e=>{e.exports=require("os")}};var t={};function __nccwpck_require__(r){var n=t[r];if(n!==undefined){return n.exports}var s=t[r]={exports:{}};var c=true;try{e[r](s,s.exports,__nccwpck_require__);c=false}finally{if(c)delete t[r]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var r={};(()=>{var e=r;Object.defineProperty(e,"__esModule",{value:true});e.extract=extract;e.parse=parse;e.parseWithComments=parseWithComments;e.print=print;e.strip=strip;function _os(){const e=__nccwpck_require__(37);_os=function(){return e};return e}function _detectNewline(){const e=_interopRequireDefault(__nccwpck_require__(381));_detectNewline=function(){return e};return e}function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}const t=/\*\/$/;const n=/^\/\*\*?/;const s=/^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;const c=/(^|\s+)\/\/([^\r\n]*)/g;const o=/^(\r?\n)+/;const i=/(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *(?![^@\r\n]*\/\/[^]*)([^@\r\n\s][^@\r\n]+?) *\r?\n/g;const a=/(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;const u=/(\r?\n|^) *\* ?/g;const p=[];function extract(e){const t=e.match(s);return t?t[0].trimLeft():""}function strip(e){const t=e.match(s);return t&&t[0]?e.substring(t[0].length):e}function parse(e){return parseWithComments(e).pragmas}function parseWithComments(e){const r=(0,_detectNewline().default)(e)??_os().EOL;e=e.replace(n,"").replace(t,"").replace(u,"$1");let s="";while(s!==e){s=e;e=e.replace(i,`${r}$1 $2${r}`)}e=e.replace(o,"").trimRight();const _=Object.create(null);const l=e.replace(a,"").replace(o,"").trimRight();let f;while(f=a.exec(e)){const e=f[2].replace(c,"");if(typeof _[f[1]]==="string"||Array.isArray(_[f[1]])){_[f[1]]=p.concat(_[f[1]],e)}else{_[f[1]]=e}}return{comments:l,pragmas:_}}function print({comments:e="",pragmas:t={}}){const r=(0,_detectNewline().default)(e)??_os().EOL;const n="/**";const s=" *";const c=" */";const o=Object.keys(t);const i=o.map((e=>printKeyValues(e,t[e]))).reduce(((e,t)=>e.concat(t)),[]).map((e=>`${s} ${e}${r}`)).join("");if(!e){if(o.length===0){return""}if(o.length===1&&!Array.isArray(t[o[0]])){const e=t[o[0]];return`${n} ${printKeyValues(o[0],e)[0]}${c}`}}const a=e.split(r).map((e=>`${s} ${e}`)).join(r)+r;return n+r+(e?a:"")+(e&&o.length?s+r:"")+i+c}function printKeyValues(e,t){return p.concat(t).map((t=>`@${e} ${t}`.trim()))}})();module.exports=r})();
\ No newline at end of file
{"name":"jest-docblock","main":"index.js","license":"MIT"}
...@@ -2167,6 +2167,15 @@ export async function ncc_https_proxy_agent(task, opts) { ...@@ -2167,6 +2167,15 @@ export async function ncc_https_proxy_agent(task, opts) {
.target('src/compiled/https-proxy-agent') .target('src/compiled/https-proxy-agent')
} }
// eslint-disable-next-line camelcase
externals['jest-docblock'] = 'next/dist/compiled/jest-docblock'
export async function ncc_jest_docblock(task, opts) {
await task
.source(relative(__dirname, require.resolve('jest-docblock')))
.ncc({ packageName: 'jest-docblock', externals })
.target('src/compiled/jest-docblock')
}
export async function precompile(task, opts) { export async function precompile(task, opts) {
await task.parallel( await task.parallel(
[ [
...@@ -2301,6 +2310,7 @@ export async function ncc(task, opts) { ...@@ -2301,6 +2310,7 @@ export async function ncc(task, opts) {
'ncc_opentelemetry_api', 'ncc_opentelemetry_api',
'ncc_http_proxy_agent', 'ncc_http_proxy_agent',
'ncc_https_proxy_agent', 'ncc_https_proxy_agent',
'ncc_jest_docblock',
'ncc_mini_css_extract_plugin', 'ncc_mini_css_extract_plugin',
], ],
opts opts
......
...@@ -460,3 +460,8 @@ declare module 'next/dist/compiled/@opentelemetry/api' { ...@@ -460,3 +460,8 @@ declare module 'next/dist/compiled/@opentelemetry/api' {
import * as m from '@opentelemetry/api' import * as m from '@opentelemetry/api'
export = m export = m
} }
declare module 'next/dist/compiled/jest-docblock' {
import m from 'jest-docblock'
export = m
}
...@@ -616,6 +616,7 @@ importers: ...@@ -616,6 +616,7 @@ importers:
image-size: 1.0.0 image-size: 1.0.0
is-docker: 2.0.0 is-docker: 2.0.0
is-wsl: 2.2.0 is-wsl: 2.2.0
jest-docblock: 29.4.3
jest-worker: 27.0.0-next.5 jest-worker: 27.0.0-next.5
json5: 2.2.3 json5: 2.2.3
jsonwebtoken: 9.0.0 jsonwebtoken: 9.0.0
...@@ -834,6 +835,7 @@ importers: ...@@ -834,6 +835,7 @@ importers:
image-size: 1.0.0 image-size: 1.0.0
is-docker: 2.0.0 is-docker: 2.0.0
is-wsl: 2.2.0 is-wsl: 2.2.0
jest-docblock: 29.4.3
jest-worker: 27.0.0-next.5 jest-worker: 27.0.0-next.5
json5: 2.2.3 json5: 2.2.3
jsonwebtoken: 9.0.0 jsonwebtoken: 9.0.0
...@@ -15502,6 +15504,13 @@ packages: ...@@ -15502,6 +15504,13 @@ packages:
detect-newline: 3.1.0 detect-newline: 3.1.0
dev: true dev: true
/jest-docblock/29.4.3:
resolution: {integrity: sha512-fzdTftThczeSD9nZ3fzA/4KkHtnmllawWrXO69vtI+L9WjEIuXWs4AmyME7lN5hU7dB0sHhuPfcKofRsUb/2Fg==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
dependencies:
detect-newline: 3.1.0
dev: true
/jest-each/27.5.1: /jest-each/27.5.1:
resolution: {integrity: sha512-1Ff6p+FbhT/bXQnEouYy00bkNSY7OUpfIcmdl8vZ31A1UUaurOLPA8a8BbJOF2RDUElwJhmeaV7LnagI+5UwNQ==} resolution: {integrity: sha512-1Ff6p+FbhT/bXQnEouYy00bkNSY7OUpfIcmdl8vZ31A1UUaurOLPA8a8BbJOF2RDUElwJhmeaV7LnagI+5UwNQ==}
engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0}
......
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
describe('next/jest', () => {
let next: NextInstance
beforeAll(async () => {
next = await createNext({
skipStart: true,
files: {
'app/page.jsx': `import { PI } from '../lib/util'
export default function Home() {
return <h1>{PI}</h1>
}`,
'app/layout.jsx': `export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}`,
'app/page.test.jsx': `import { render, screen } from '@testing-library/react'
import '@testing-library/jest-dom'
import Page from './page'
it('works from client-side code', () => {
render(<Page />)
expect(screen.getByRole('heading')).toHaveTextContent('3.14')
})`,
'lib/util.js': `/** @jest-environment node */
import 'server-only'
export const PI = 3.14;`,
'lib/utils.test.ts': `import { PI } from './util'
it('works from server-side code', () => {
expect(PI).toEqual(3.14)
})`,
'jest.config.js': `module.exports = require('next/jest')({ dir: './' })({ testEnvironment: 'jsdom' })`,
},
buildCommand: `yarn jest`,
dependencies: {
'@types/react': 'latest',
'@testing-library/jest-dom': '5.16.5',
'@testing-library/react': '13.0.0',
jest: '27.4.7',
},
})
})
afterAll(() => next.destroy())
it('can run test against server side components', async () => {
try {
await next.start()
} finally {
expect(next.cliOutput).toInclude('Tests: 2 passed, 2 total')
}
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment