Unverified Commit 725fbc29 authored by John Daly's avatar John Daly Committed by GitHub

[next/jest] Support path aliases from `tsconfig`/`jsconfig` (#45815)

<!--
Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:
-->

# Description

fixes #31159
fixes #44553

Path aliases defined in `tsconfig.json` or `jsconfig.json` are not
automatically configured to work with Jest. This means that these
aliases have to be defined in multiple places.

This PR configures the SWC Jest transform to handle the `baseUrl` and
`paths`, so that users don't need to configure a `moduleNameMapper` for
Jest.

~This PR intends to make the experience more seamless by automatically
configuring Jest's `moduleNameMapper` and `moduleDirectories` based on
the settings in a project's `tsconfig`/`jsconfig`.~

~Users will be able to supply their own configuration for these fields,
if they have use-cases that require manual configuration.~

~The implementation is taken from the [`paths-to-module-name-mapper`
function in
`ts-jest`](https://github.com/kulshekhar/ts-jest/blob/5a0880add0da8d71900eee20c7642e6be65f6a66/src/config/paths-to-module-name-mapper.ts).~

## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the
feature request has been accepted for implementation before opening a
PR.
- [x] Related issues linked using `fixes #number`
- [ ]
[e2e](https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have a helpful link attached, see
[`contributing.md`](https://github.com/vercel/next.js/blob/canary/contributing.md)

## Documentation / Examples

- [ ] Make sure the linting passes by running `pnpm build && pnpm lint`
- [ ] The "examples guidelines" are followed from [our contributing
doc](https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md)
parent 9dfbe931
...@@ -320,17 +320,7 @@ const createJestConfig = nextJest({ ...@@ -320,17 +320,7 @@ const createJestConfig = nextJest({
const customJestConfig = { const customJestConfig = {
// Add more setup options before each test is run // Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], // setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'],
// If you're using [Module Path Aliases](https://nextjs.org/docs/advanced-features/module-path-aliases),
// you will have to add the moduleNameMapper in order for jest to resolve your absolute paths.
// The paths have to be matching with the paths option within the compilerOptions in the tsconfig.json
// For example:
moduleNameMapper: {
'@/(.*)$': '<rootDir>/src/$1',
},
testEnvironment: 'jest-environment-jsdom', testEnvironment: 'jest-environment-jsdom',
} }
......
...@@ -183,11 +183,10 @@ export function getJestSWCOptions({ ...@@ -183,11 +183,10 @@ export function getJestSWCOptions({
esm, esm,
nextConfig, nextConfig,
jsConfig, jsConfig,
resolvedBaseUrl,
pagesDir, pagesDir,
hasServerComponents, hasServerComponents,
}: // This is not passed yet as "paths" resolving needs a test first }: any) {
// resolvedBaseUrl,
any) {
let baseOptions = getBaseSWCOptions({ let baseOptions = getBaseSWCOptions({
filename, filename,
jest: true, jest: true,
...@@ -197,7 +196,7 @@ any) { ...@@ -197,7 +196,7 @@ any) {
nextConfig, nextConfig,
jsConfig, jsConfig,
hasServerComponents, hasServerComponents,
// resolvedBaseUrl, resolvedBaseUrl,
}) })
const isNextDist = nextDistPath.test(filename) const isNextDist = nextDistPath.test(filename)
......
...@@ -10,10 +10,6 @@ const customJestConfig = { ...@@ -10,10 +10,6 @@ const customJestConfig = {
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'], moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom', testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
// When changing these, also look at the tsconfig!
'^types/(.+)$': '<rootDir>/types/$1',
},
} }
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
......
import { RelayEnvironmentProvider } from 'react-relay/hooks' import { RelayEnvironmentProvider } from 'react-relay/hooks'
import RelayEnvironment from '../components/environment' import RelayEnvironment from '@/components/environment'
export default function MyApp({ Component, pageProps }) { export default function MyApp({ Component, pageProps }) {
return ( return (
......
import { graphql, useRelayEnvironment, QueryRenderer } from 'react-relay' import { graphql, useRelayEnvironment, QueryRenderer } from 'react-relay'
import type { pagesQueryResponse } from '../types/pagesQuery.graphql' import type { pagesQueryResponse } from '@/types/pagesQuery.graphql'
function Component() { function Component() {
const env = useRelayEnvironment() const env = useRelayEnvironment()
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
"paths": { "paths": {
"types/*": ["./types/*"] "@/*": ["./*"]
} }
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tests/entry.test.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tests/entry.test.tsx"],
......
...@@ -17,7 +17,7 @@ describe('next/jest', () => { ...@@ -17,7 +17,7 @@ describe('next/jest', () => {
import { RelayEnvironmentProvider } from 'react-relay' import { RelayEnvironmentProvider } from 'react-relay'
import { createMockEnvironment, MockPayloadGenerator } from 'relay-test-utils' import { createMockEnvironment, MockPayloadGenerator } from 'relay-test-utils'
import Page from '../pages' import Page from '@/pages'
describe('test graphql tag transformation', () => { describe('test graphql tag transformation', () => {
it('should work', async () => { it('should work', async () => {
......
...@@ -10,10 +10,6 @@ const customJestConfig = { ...@@ -10,10 +10,6 @@ const customJestConfig = {
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work // if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'], moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom', testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
// When changing these, also look at the tsconfig!
'^types/(.+)$': '<rootDir>/types/$1',
},
} }
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async // createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
......
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"incremental": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"paths": {
"@/*": ["./*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tests/entry.test.tsx"],
"exclude": ["node_modules"]
}
...@@ -12,11 +12,11 @@ describe('next/jest', () => { ...@@ -12,11 +12,11 @@ describe('next/jest', () => {
next = await createNext({ next = await createNext({
files: { files: {
pages: new FileRef(path.join(appDir, 'pages')), pages: new FileRef(path.join(appDir, 'pages')),
'tests/index.test.js': ` 'tests/index.test.tsx': `
import { render as renderFn, waitFor } from '@testing-library/react' import { render as renderFn, waitFor } from '@testing-library/react'
import '@testing-library/jest-dom/extend-expect'; import '@testing-library/jest-dom/extend-expect';
import Page from '../pages' import Page from '@/pages'
describe('testid', () => { describe('testid', () => {
it('data-testid should be available in the test', async () => { it('data-testid should be available in the test', async () => {
...@@ -30,6 +30,7 @@ describe('next/jest', () => { ...@@ -30,6 +30,7 @@ describe('next/jest', () => {
`, `,
'jest.config.js': new FileRef(path.join(appDir, 'jest.config.js')), 'jest.config.js': new FileRef(path.join(appDir, 'jest.config.js')),
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')), 'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
'tsconfig.json': new FileRef(path.join(appDir, 'tsconfig.json')),
}, },
dependencies: { dependencies: {
jest: '27.4.7', jest: '27.4.7',
...@@ -40,7 +41,8 @@ describe('next/jest', () => { ...@@ -40,7 +41,8 @@ describe('next/jest', () => {
packageJson: { packageJson: {
scripts: { scripts: {
// Runs jest and bails if jest fails // Runs jest and bails if jest fails
build: 'yarn jest --forceExit tests/index.test.js && yarn next build', build:
'yarn jest --forceExit tests/index.test.tsx && yarn next build',
}, },
}, },
buildCommand: `yarn build`, buildCommand: `yarn build`,
......
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