Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Experimental next/jest config helper
Co-Authored-By: Maia Teegarden <dev@padmaia.rocks>
- Loading branch information
1 parent
764e29c
commit a18c24d
Showing
11 changed files
with
301 additions
and
76 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,16 +1,16 @@ | ||
const path = require('path') | ||
const nextJest = require('next/jest') | ||
|
||
module.exports = { | ||
const createJestConfig = nextJest() | ||
|
||
// Any custom config you want to pass to Jest | ||
const customJestConfig = { | ||
testMatch: ['**/*.test.js', '**/*.test.ts', '**/*.test.tsx'], | ||
setupFilesAfterEnv: ['<rootDir>/jest-setup-after-env.ts'], | ||
verbose: true, | ||
rootDir: 'test', | ||
modulePaths: ['<rootDir>/lib'], | ||
transformIgnorePatterns: ['/node_modules/', '/next[/\\\\]dist/', '/.next/'], | ||
transform: { | ||
'.+\\.(t|j)sx?$': [ | ||
// this matches our SWC options used in https://github.com/vercel/next.js/blob/canary/packages/next/taskfile-swc.js | ||
path.join(__dirname, './packages/next/jest.js'), | ||
], | ||
}, | ||
transformIgnorePatterns: ['/next[/\\\\]dist/'], | ||
} | ||
|
||
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async | ||
module.exports = createJestConfig(customJestConfig) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
module.exports = 'test-file-stub' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
module.exports = {} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,130 @@ | ||
import { loadEnvConfig } from '@next/env' | ||
import { resolve, join } from 'path' | ||
import loadConfig from '../../server/config' | ||
import { PHASE_TEST } from '../../shared/lib/constants' | ||
// import loadJsConfig from '../load-jsconfig' | ||
import * as Log from '../output/log' | ||
|
||
async function getConfig(dir: string) { | ||
const conf = await loadConfig(PHASE_TEST, dir) | ||
return conf | ||
} | ||
|
||
/** | ||
* Loads closest package.json in the directory hierarchy | ||
*/ | ||
function loadClosestPackageJson(dir: string, attempts = 1): any { | ||
if (attempts > 5) { | ||
throw new Error("Can't resolve main package.json file") | ||
} | ||
var mainPath = attempts === 1 ? './' : Array(attempts).join('../') | ||
try { | ||
return require(join(dir, mainPath + 'package.json')) | ||
} catch (e) { | ||
return loadClosestPackageJson(dir, attempts + 1) | ||
} | ||
} | ||
|
||
/* | ||
// Usage in jest.config.js | ||
const nextJest = require('next/jest'); | ||
// Optionally provide path to Next.js app which will enable loading next.config.js and .env files | ||
const createJestConfig = nextJest({ dir }) | ||
// Any custom config you want to pass to Jest | ||
const customJestConfig = { | ||
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'], | ||
} | ||
// createJestConfig is exported in this way to ensure that next/jest can load the Next.js config which is async | ||
module.exports = createJestConfig(customJestConfig) | ||
*/ | ||
module.exports = function nextJest(options: { dir?: string } = {}) { | ||
// createJestConfig | ||
return (customJestConfig: any) => { | ||
// Function that is provided as the module.exports of jest.config.js | ||
// Will be called and awaited by Jest | ||
return async () => { | ||
let nextConfig | ||
let paths | ||
let resolvedBaseUrl | ||
let isEsmProject = false | ||
if (options.dir) { | ||
const resolvedDir = resolve(options.dir) | ||
const packageConfig = loadClosestPackageJson(resolvedDir) | ||
isEsmProject = packageConfig.type === 'module' | ||
|
||
nextConfig = await getConfig(resolvedDir) | ||
loadEnvConfig(resolvedDir, false, Log) | ||
// TODO: revisit when bug in SWC is fixed that strips `.css` | ||
// const result = await loadJsConfig(resolvedDir, nextConfig) | ||
// paths = result?.jsConfig?.compilerOptions?.paths | ||
// resolvedBaseUrl = result.resolvedBaseUrl | ||
} | ||
// Ensure provided async config is supported | ||
const resolvedJestConfig = | ||
typeof customJestConfig === 'function' | ||
? await customJestConfig() | ||
: customJestConfig | ||
|
||
return { | ||
...resolvedJestConfig, | ||
|
||
moduleNameMapper: { | ||
// Handle CSS imports (with CSS modules) | ||
// https://jestjs.io/docs/webpack#mocking-css-modules | ||
'^.+\\.module\\.(css|sass|scss)$': | ||
require.resolve('./object-proxy.js'), | ||
|
||
// Handle CSS imports (without CSS modules) | ||
'^.+\\.(css|sass|scss)$': require.resolve('./__mocks__/styleMock.js'), | ||
|
||
// Handle image imports | ||
'^.+\\.(jpg|jpeg|png|gif|webp|avif|svg)$': require.resolve( | ||
`./__mocks__/fileMock.js` | ||
), | ||
|
||
// Custom config will be able to override the default mappings | ||
...(resolvedJestConfig.moduleNameMapper || {}), | ||
}, | ||
testPathIgnorePatterns: [ | ||
// Don't look for tests in node_modules | ||
'/node_modules/', | ||
// Don't look for tests in the the Next.js build output | ||
'/.next/', | ||
// Custom config can append to testPathIgnorePatterns but not modify it | ||
// This is to ensure `.next` and `node_modules` are always excluded | ||
...(resolvedJestConfig.testPathIgnorePatterns || []), | ||
], | ||
|
||
transform: { | ||
// Use SWC to compile tests | ||
'^.+\\.(js|jsx|ts|tsx)$': [ | ||
require.resolve('../swc/jest-transformer'), | ||
{ | ||
styledComponents: | ||
nextConfig && nextConfig.experimental.styledComponents, | ||
paths, | ||
resolvedBaseUrl: resolvedBaseUrl, | ||
isEsmProject, | ||
}, | ||
], | ||
// Allow for appending/overriding the default transforms | ||
...(resolvedJestConfig.transform || {}), | ||
}, | ||
|
||
transformIgnorePatterns: [ | ||
// To match Next.js behavior node_modules is not transformed | ||
'/node_modules/', | ||
// CSS modules are mocked so they don't need to be transformed | ||
'^.+\\.module\\.(css|sass|scss)$', | ||
|
||
// Custom config can append to transformIgnorePatterns but not modify it | ||
// This is to ensure `node_modules` and .module.css/sass/scss are always excluded | ||
...(resolvedJestConfig.transformIgnorePatterns || []), | ||
], | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
/* | ||
The MIT License (MIT) | ||
Copyright (c) 2015 Keyan Zhang | ||
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. | ||
*/ | ||
|
||
// This file is largely based on https://github.com/keyz/identity-obj-proxy | ||
// Excludes the polyfill for below Node.js 6 | ||
export default new Proxy( | ||
{}, | ||
{ | ||
get: function getter(target, key) { | ||
if (key === '__esModule') { | ||
return false | ||
} | ||
return key | ||
}, | ||
} | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
import path from 'path' | ||
import { fileExists } from '../lib/file-exists' | ||
import { NextConfigComplete } from '../server/config-shared' | ||
import * as Log from './output/log' | ||
import { getTypeScriptConfiguration } from '../lib/typescript/getTypeScriptConfiguration' | ||
import { readFileSync } from 'fs' | ||
import isError from '../lib/is-error' | ||
import { codeFrameColumns } from 'next/dist/compiled/babel/code-frame' | ||
|
||
let TSCONFIG_WARNED = false | ||
|
||
function parseJsonFile(filePath: string) { | ||
const JSON5 = require('next/dist/compiled/json5') | ||
const contents = readFileSync(filePath, 'utf8') | ||
|
||
// Special case an empty file | ||
if (contents.trim() === '') { | ||
return {} | ||
} | ||
|
||
try { | ||
return JSON5.parse(contents) | ||
} catch (err) { | ||
if (!isError(err)) throw err | ||
const codeFrame = codeFrameColumns( | ||
String(contents), | ||
{ | ||
start: { | ||
line: (err as Error & { lineNumber?: number }).lineNumber || 0, | ||
column: (err as Error & { columnNumber?: number }).columnNumber || 0, | ||
}, | ||
}, | ||
{ message: err.message, highlightCode: true } | ||
) | ||
throw new Error(`Failed to parse "${filePath}":\n${codeFrame}`) | ||
} | ||
} | ||
|
||
export default async function loadJsConfig( | ||
dir: string, | ||
config: NextConfigComplete | ||
) { | ||
let typeScriptPath: string | undefined | ||
try { | ||
typeScriptPath = require.resolve('typescript', { paths: [dir] }) | ||
} catch (_) {} | ||
const tsConfigPath = path.join(dir, config.typescript.tsconfigPath) | ||
const useTypeScript = Boolean( | ||
typeScriptPath && (await fileExists(tsConfigPath)) | ||
) | ||
|
||
let jsConfig | ||
// jsconfig is a subset of tsconfig | ||
if (useTypeScript) { | ||
if ( | ||
config.typescript.tsconfigPath !== 'tsconfig.json' && | ||
TSCONFIG_WARNED === false | ||
) { | ||
TSCONFIG_WARNED = true | ||
Log.info(`Using tsconfig file: ${config.typescript.tsconfigPath}`) | ||
} | ||
|
||
const ts = (await Promise.resolve( | ||
require(typeScriptPath!) | ||
)) as typeof import('typescript') | ||
const tsConfig = await getTypeScriptConfiguration(ts, tsConfigPath, true) | ||
jsConfig = { compilerOptions: tsConfig.options } | ||
} | ||
|
||
const jsConfigPath = path.join(dir, 'jsconfig.json') | ||
if (!useTypeScript && (await fileExists(jsConfigPath))) { | ||
jsConfig = parseJsonFile(jsConfigPath) | ||
} | ||
|
||
let resolvedBaseUrl | ||
if (jsConfig?.compilerOptions?.baseUrl) { | ||
resolvedBaseUrl = path.resolve(dir, jsConfig.compilerOptions.baseUrl) | ||
} | ||
return { | ||
jsConfig, | ||
resolvedBaseUrl, | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.