Unverified Commit 5aa54b33 authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

Add pagesDir to Jest transformer (#36599)

Fixes #35469

Adds `pagesDir` which is required for the Relay transform.

Added a test case based on https://github.com/hanford/relay-swc-jest.



## Bug

- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [ ] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`
Co-authored-by: 's avatarJJ Kasper <22380829+ijjk@users.noreply.github.com>
parent bd3dfe1f
...@@ -4,6 +4,7 @@ import loadConfig from '../../server/config' ...@@ -4,6 +4,7 @@ import loadConfig from '../../server/config'
import { PHASE_TEST } from '../../shared/lib/constants' import { PHASE_TEST } from '../../shared/lib/constants'
import loadJsConfig from '../load-jsconfig' import loadJsConfig from '../load-jsconfig'
import * as Log from '../output/log' import * as Log from '../output/log'
import { findPagesDir } from '../../lib/find-pages-dir'
async function getConfig(dir: string) { async function getConfig(dir: string) {
const conf = await loadConfig(PHASE_TEST, dir) const conf = await loadConfig(PHASE_TEST, dir)
...@@ -50,8 +51,11 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -50,8 +51,11 @@ export default function nextJest(options: { dir?: string } = {}) {
let jsConfig let jsConfig
let resolvedBaseUrl let resolvedBaseUrl
let isEsmProject = false let isEsmProject = false
let pagesDir
if (options.dir) { if (options.dir) {
const resolvedDir = resolve(options.dir) const resolvedDir = resolve(options.dir)
pagesDir = findPagesDir(resolvedDir)
const packageConfig = loadClosestPackageJson(resolvedDir) const packageConfig = loadClosestPackageJson(resolvedDir)
isEsmProject = packageConfig.type === 'module' isEsmProject = packageConfig.type === 'module'
...@@ -108,6 +112,7 @@ export default function nextJest(options: { dir?: string } = {}) { ...@@ -108,6 +112,7 @@ export default function nextJest(options: { dir?: string } = {}) {
jsConfig, jsConfig,
resolvedBaseUrl, resolvedBaseUrl,
isEsmProject, isEsmProject,
pagesDir,
}, },
], ],
// Allow for appending/overriding the default transforms // Allow for appending/overriding the default transforms
......
...@@ -47,6 +47,7 @@ module.exports = { ...@@ -47,6 +47,7 @@ module.exports = {
nextConfig: inputOptions.nextConfig, nextConfig: inputOptions.nextConfig,
jsConfig: inputOptions.jsConfig, jsConfig: inputOptions.jsConfig,
resolvedBaseUrl: inputOptions.resolvedBaseUrl, resolvedBaseUrl: inputOptions.resolvedBaseUrl,
pagesDir: inputOptions.pagesDir,
esm: esm:
isSupportEsm && isSupportEsm &&
isEsm(Boolean(inputOptions.isEsmProject), filename, jestConfig), isEsm(Boolean(inputOptions.isEsmProject), filename, jestConfig),
......
...@@ -145,6 +145,7 @@ export function getJestSWCOptions({ ...@@ -145,6 +145,7 @@ export function getJestSWCOptions({
esm, esm,
nextConfig, nextConfig,
jsConfig, jsConfig,
pagesDir,
// This is not passed yet as "paths" resolving needs a test first // This is not passed yet as "paths" resolving needs a test first
// resolvedBaseUrl, // resolvedBaseUrl,
}) { }) {
...@@ -174,6 +175,7 @@ export function getJestSWCOptions({ ...@@ -174,6 +175,7 @@ export function getJestSWCOptions({
}, },
disableNextSsg: true, disableNextSsg: true,
disablePageConfig: true, disablePageConfig: true,
pagesDir,
} }
} }
......
...@@ -7,7 +7,7 @@ import { NextStartInstance } from './next-modes/next-start' ...@@ -7,7 +7,7 @@ import { NextStartInstance } from './next-modes/next-start'
import { NextDeployInstance } from './next-modes/next-deploy' import { NextDeployInstance } from './next-modes/next-deploy'
// increase timeout to account for yarn install time // increase timeout to account for yarn install time
jest.setTimeout((process.platform === 'win32' ? 240 : 180) * 1000) jest.setTimeout(240 * 1000)
const testsFolder = path.join(__dirname, '..') const testsFolder = path.join(__dirname, '..')
......
...@@ -5,6 +5,12 @@ import { renderViaHTTP } from 'next-test-utils' ...@@ -5,6 +5,12 @@ import { renderViaHTTP } from 'next-test-utils'
describe('next/jest', () => { describe('next/jest', () => {
let next: NextInstance let next: NextInstance
if (process.env.NEXT_TEST_REACT_VERSION === '^17') {
// react testing library is specific to react version
it('should bail on react v17', () => {})
return
}
beforeAll(async () => { beforeAll(async () => {
next = await createNext({ next = await createNext({
files: { files: {
......
import { Environment, Network, RecordSource, Store } from 'relay-runtime'
async function fetchGraphQL(text, variables) {
return new Promise((next) => {
const res = () => {
return next({ data: { viewer: { user: { id: '123', name: 'Foo' } } } })
}
setTimeout(res, 1000)
})
}
// Relay passes a "params" object with the query name and text. So we define a helper function
// to call our fetchGraphQL utility with params.text.
async function fetchRelay(params, variables) {
return await fetchGraphQL(params.text, variables)
}
// Export a singleton instance of Relay Environment configured with our network function:
export default new Environment({
network: Network.create(fetchRelay),
store: new Store(new RecordSource()),
})
const nextJest = require('next/jest')
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const customJestConfig = {
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
moduleDirectories: ['node_modules', '<rootDir>/'],
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
module.exports = createJestConfig(customJestConfig)
type Query {
viewer(after: String, before: String, first: Int, last: Int): Viewer!
node(id: ID!): Node
}
type Viewer implements Node {
id: ID!
user: User!
}
interface Node {
id: ID!
}
type User implements Node {
id: ID!
name: String!
title: String!
}
module.exports = {
compiler: {
relay: {
src: './',
artifactDirectory: './types',
language: 'typescript',
},
},
}
import { RelayEnvironmentProvider } from 'react-relay/hooks'
import RelayEnvironment from '../components/environment'
export default function MyApp({ Component, pageProps }) {
return (
<RelayEnvironmentProvider environment={RelayEnvironment}>
<Component {...pageProps} />
</RelayEnvironmentProvider>
)
}
import { graphql, useRelayEnvironment, QueryRenderer } from 'react-relay'
import type { pagesQueryResponse } from '../types/pagesQuery.graphql'
function Component() {
const env = useRelayEnvironment()
return (
<QueryRenderer
environment={env}
query={graphql`
query pagesQuery {
viewer {
user {
id
name
}
}
}
`}
render={({ props }: { props: pagesQueryResponse }) => {
if (props) {
return (
<div>
Data requested: <span>{props.viewer.user.id}</span>
</div>
)
}
return <div>Loading...</div>
}}
/>
)
}
export default Component
{
"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": {
"types/*": ["./types/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "tests/entry.test.tsx"],
"exclude": ["node_modules"]
}
/**
* @generated SignedSource<<a6468d297da1928100bce80db9f1b8ab>>
* @lightSyntaxTransform
* @nogrep
*/
/* tslint:disable */
/* eslint-disable */
// @ts-nocheck
import { ConcreteRequest, Query } from 'relay-runtime'
export type pagesQuery$variables = {}
export type pagesQueryVariables = pagesQuery$variables
export type pagesQuery$data = {
readonly viewer: {
readonly user: {
readonly id: string
readonly name: string
}
}
}
export type pagesQueryResponse = pagesQuery$data
export type pagesQuery = {
variables: pagesQueryVariables
response: pagesQuery$data
}
const node: ConcreteRequest = (function () {
var v0 = {
alias: null,
args: null,
kind: 'ScalarField',
name: 'id',
storageKey: null,
},
v1 = {
alias: null,
args: null,
concreteType: 'User',
kind: 'LinkedField',
name: 'user',
plural: false,
selections: [
v0 /*: any*/,
{
alias: null,
args: null,
kind: 'ScalarField',
name: 'name',
storageKey: null,
},
],
storageKey: null,
}
return {
fragment: {
argumentDefinitions: [],
kind: 'Fragment',
metadata: null,
name: 'pagesQuery',
selections: [
{
alias: null,
args: null,
concreteType: 'Viewer',
kind: 'LinkedField',
name: 'viewer',
plural: false,
selections: [v1 /*: any*/],
storageKey: null,
},
],
type: 'Query',
abstractKey: null,
},
kind: 'Request',
operation: {
argumentDefinitions: [],
kind: 'Operation',
name: 'pagesQuery',
selections: [
{
alias: null,
args: null,
concreteType: 'Viewer',
kind: 'LinkedField',
name: 'viewer',
plural: false,
selections: [v1 /*: any*/, v0 /*: any*/],
storageKey: null,
},
],
},
params: {
cacheID: '5a14ce729d0deb2c3170bcdcba33a61a',
id: null,
metadata: {},
name: 'pagesQuery',
operationKind: 'query',
text: 'query pagesQuery {\n viewer {\n user {\n id\n name\n }\n id\n }\n}\n',
},
}
})()
;(node as any).hash = '00b43dedd685e716dda36f66f4d5e30e'
export default node
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import path from 'path'
const appDir = path.join(__dirname, 'app')
describe('next/jest', () => {
let next: NextInstance
if (process.env.NEXT_TEST_REACT_VERSION === '^17') {
// react testing library is specific to react version
it('should bail on react v17', () => {})
return
}
beforeAll(async () => {
next = await createNext({
files: {
components: new FileRef(path.join(appDir, 'components')),
pages: new FileRef(path.join(appDir, 'pages')),
'tests/entry.test.tsx': `
import { render as renderFn, waitFor } from '@testing-library/react'
import { RelayEnvironmentProvider } from 'react-relay'
import { createMockEnvironment, MockPayloadGenerator } from 'relay-test-utils'
import Page from '../pages'
describe('test graphql tag transformation', () => {
it('should work', async () => {
let environment = createMockEnvironment()
const { getByText } = renderFn(
<RelayEnvironmentProvider environment={environment}>
<Page />
</RelayEnvironmentProvider>
)
environment.mock.resolveMostRecentOperation((operation) => {
return MockPayloadGenerator.generate(operation)
})
await waitFor(() => getByText('Data requested:'))
expect(getByText('Data requested:')).not.toBe(null)
})
})
`,
types: new FileRef(path.join(appDir, 'types')),
'jest.config.js': new FileRef(path.join(appDir, 'jest.config.js')),
'next.config.js': new FileRef(path.join(appDir, 'next.config.js')),
'tsconfig.json': new FileRef(path.join(appDir, 'tsconfig.json')),
'main.graphql': new FileRef(path.join(appDir, 'main.graphql')),
},
dependencies: {
jest: '27.4.7',
'react-relay': '^13.2.0',
'@testing-library/react': '^13.1.1',
'@types/jest': '^27.4.1',
'babel-jest': '^27.5.1',
'babel-plugin-relay': '^13.2.0',
jsdom: '^19.0.0',
'relay-compiler': '^13.0.1',
'relay-test-utils': '^13.0.2',
typescript: '^4.6.3',
},
packageJson: {
scripts: {
// Runs jest and bails if jest fails
build:
'yarn jest --forceExit tests/entry.test.tsx && yarn next build',
},
},
buildCommand: `yarn build`,
})
})
afterAll(() => next.destroy())
it('should work', async () => {
// Suite fails if `jest` fails during `build`
expect(typeof '').toBe('string')
})
})
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