Skip to content

Commit e1bca72

Browse files
authored
test(examples): add example React app with ts-jest (#3097)
1 parent d430277 commit e1bca72

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+35847
-38
lines changed

e2e/ast-transformers/hoist-jest/__tests__/integration.test.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ jest.mock('../__test_modules__/f', () => {
4141
},
4242
}
4343
})
44-
jest.mock(`../__test_modules__/jest-backticks`)
44+
jest.mock('../__test_modules__/jest-backticks')
4545
jest.mock('virtual-module', () => 'kiwi', { virtual: true })
4646
// This has types that should be ignored by the out-of-scope variables check.
4747
jest.mock('has-flow-types', () => () => 3, {

examples/react/.gitignore

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*

examples/react/README.md

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Getting Started with Create React App
2+
3+
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
4+
5+
## Available Scripts
6+
7+
In the project directory, you can run:
8+
9+
### `yarn start`
10+
11+
Runs the app in the development mode.\
12+
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
13+
14+
The page will reload if you make edits.\
15+
You will also see any lint errors in the console.
16+
17+
### `yarn test`
18+
19+
Launches the test runner in the interactive watch mode.\
20+
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
21+
22+
### `yarn build`
23+
24+
Builds the app for production to the `build` folder.\
25+
It correctly bundles React in production mode and optimizes the build for the best performance.
26+
27+
The build is minified and the filenames include the hashes.\
28+
Your app is ready to be deployed!
29+
30+
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
31+
32+
### `yarn eject`
33+
34+
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
35+
36+
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
37+
38+
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
39+
40+
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
41+
42+
## Learn More
43+
44+
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
45+
46+
To learn React, check out the [React documentation](https://reactjs.org/).

examples/react/config/env.js

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
const fs = require('fs')
2+
const path = require('path')
3+
const paths = require('./paths')
4+
5+
// Make sure that including paths.js after env.js will read .env variables.
6+
delete require.cache[require.resolve('./paths')]
7+
8+
const NODE_ENV = process.env.NODE_ENV
9+
if (!NODE_ENV) {
10+
throw new Error('The NODE_ENV environment variable is required but was not specified.')
11+
}
12+
13+
// https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use
14+
const dotenvFiles = [
15+
`${paths.dotenv}.${NODE_ENV}.local`,
16+
// Don't include `.env.local` for `test` environment
17+
// since normally you expect tests to produce the same
18+
// results for everyone
19+
NODE_ENV !== 'test' && `${paths.dotenv}.local`,
20+
`${paths.dotenv}.${NODE_ENV}`,
21+
paths.dotenv,
22+
].filter(Boolean)
23+
24+
// Load environment variables from .env* files. Suppress warnings using silent
25+
// if this file is missing. dotenv will never modify any environment variables
26+
// that have already been set. Variable expansion is supported in .env files.
27+
// https://github.com/motdotla/dotenv
28+
// https://github.com/motdotla/dotenv-expand
29+
dotenvFiles.forEach((dotenvFile) => {
30+
if (fs.existsSync(dotenvFile)) {
31+
require('dotenv-expand')(
32+
require('dotenv').config({
33+
path: dotenvFile,
34+
})
35+
)
36+
}
37+
})
38+
39+
// We support resolving modules according to `NODE_PATH`.
40+
// This lets you use absolute paths in imports inside large monorepos:
41+
// https://github.com/facebook/create-react-app/issues/253.
42+
// It works similar to `NODE_PATH` in Node itself:
43+
// https://nodejs.org/api/modules.html#modules_loading_from_the_global_folders
44+
// Note that unlike in Node, only *relative* paths from `NODE_PATH` are honored.
45+
// Otherwise, we risk importing Node.js core modules into an app instead of webpack shims.
46+
// https://github.com/facebook/create-react-app/issues/1023#issuecomment-265344421
47+
// We also resolve them to make sure all tools using them work consistently.
48+
const appDirectory = fs.realpathSync(process.cwd())
49+
process.env.NODE_PATH = (process.env.NODE_PATH || '')
50+
.split(path.delimiter)
51+
.filter((folder) => folder && !path.isAbsolute(folder))
52+
.map((folder) => path.resolve(appDirectory, folder))
53+
.join(path.delimiter)
54+
55+
// Grab NODE_ENV and REACT_APP_* environment variables and prepare them to be
56+
// injected into the application via DefinePlugin in webpack configuration.
57+
const REACT_APP = /^REACT_APP_/i
58+
59+
function getClientEnvironment(publicUrl) {
60+
const raw = Object.keys(process.env)
61+
.filter((key) => REACT_APP.test(key))
62+
.reduce(
63+
(env, key) => {
64+
env[key] = process.env[key]
65+
return env
66+
},
67+
{
68+
// Useful for determining whether we’re running in production mode.
69+
// Most importantly, it switches React into the correct mode.
70+
NODE_ENV: process.env.NODE_ENV || 'development',
71+
// Useful for resolving the correct path to static assets in `public`.
72+
// For example, <img src={process.env.PUBLIC_URL + '/img/logo.png'} />.
73+
// This should only be used as an escape hatch. Normally you would put
74+
// images into the `src` and `import` them in code to get their paths.
75+
PUBLIC_URL: publicUrl,
76+
// We support configuring the sockjs pathname during development.
77+
// These settings let a developer run multiple simultaneous projects.
78+
// They are used as the connection `hostname`, `pathname` and `port`
79+
// in webpackHotDevClient. They are used as the `sockHost`, `sockPath`
80+
// and `sockPort` options in webpack-dev-server.
81+
WDS_SOCKET_HOST: process.env.WDS_SOCKET_HOST,
82+
WDS_SOCKET_PATH: process.env.WDS_SOCKET_PATH,
83+
WDS_SOCKET_PORT: process.env.WDS_SOCKET_PORT,
84+
// Whether or not react-refresh is enabled.
85+
// react-refresh is not 100% stable at this time,
86+
// which is why it's disabled by default.
87+
// It is defined here so it is available in the webpackHotDevClient.
88+
FAST_REFRESH: process.env.FAST_REFRESH !== 'false',
89+
}
90+
)
91+
// Stringify all values so we can feed into webpack DefinePlugin
92+
const stringified = {
93+
'process.env': Object.keys(raw).reduce((env, key) => {
94+
env[key] = JSON.stringify(raw[key])
95+
return env
96+
}, {}),
97+
}
98+
99+
return { raw, stringified }
100+
}
101+
102+
module.exports = getClientEnvironment
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
const fs = require('fs')
2+
const path = require('path')
3+
const crypto = require('crypto')
4+
const chalk = require('react-dev-utils/chalk')
5+
const paths = require('./paths')
6+
7+
// Ensure the certificate and key provided are valid and if not
8+
// throw an easy to debug error
9+
function validateKeyAndCerts({ cert, key, keyFile, crtFile }) {
10+
let encrypted
11+
try {
12+
// publicEncrypt will throw an error with an invalid cert
13+
encrypted = crypto.publicEncrypt(cert, Buffer.from('test'))
14+
} catch (err) {
15+
throw new Error(`The certificate "${chalk.yellow(crtFile)}" is invalid.\n${err.message}`)
16+
}
17+
18+
try {
19+
// privateDecrypt will throw an error with an invalid key
20+
crypto.privateDecrypt(key, encrypted)
21+
} catch (err) {
22+
throw new Error(`The certificate key "${chalk.yellow(keyFile)}" is invalid.\n${err.message}`)
23+
}
24+
}
25+
26+
// Read file and throw an error if it doesn't exist
27+
function readEnvFile(file, type) {
28+
if (!fs.existsSync(file)) {
29+
throw new Error(
30+
`You specified ${chalk.cyan(type)} in your env, but the file "${chalk.yellow(file)}" can't be found.`
31+
)
32+
}
33+
return fs.readFileSync(file)
34+
}
35+
36+
// Get the https config
37+
// Return cert files if provided in env, otherwise just true or false
38+
function getHttpsConfig() {
39+
const { SSL_CRT_FILE, SSL_KEY_FILE, HTTPS } = process.env
40+
const isHttps = HTTPS === 'true'
41+
42+
if (isHttps && SSL_CRT_FILE && SSL_KEY_FILE) {
43+
const crtFile = path.resolve(paths.appPath, SSL_CRT_FILE)
44+
const keyFile = path.resolve(paths.appPath, SSL_KEY_FILE)
45+
const config = {
46+
cert: readEnvFile(crtFile, 'SSL_CRT_FILE'),
47+
key: readEnvFile(keyFile, 'SSL_KEY_FILE'),
48+
}
49+
50+
validateKeyAndCerts({ ...config, keyFile, crtFile })
51+
return config
52+
}
53+
return isHttps
54+
}
55+
56+
module.exports = getHttpsConfig
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const babelJest = require('babel-jest')
2+
3+
const hasJsxRuntime = (() => {
4+
if (process.env.DISABLE_NEW_JSX_TRANSFORM === 'true') {
5+
return false
6+
}
7+
8+
try {
9+
require.resolve('react/jsx-runtime')
10+
return true
11+
} catch (e) {
12+
return false
13+
}
14+
})()
15+
16+
module.exports = babelJest.default.createTransformer({
17+
presets: [
18+
[
19+
require.resolve('babel-preset-react-app'),
20+
{
21+
runtime: hasJsxRuntime ? 'automatic' : 'classic',
22+
},
23+
],
24+
],
25+
babelrc: false,
26+
configFile: false,
27+
})
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// This is a custom Jest transformer turning style imports into empty objects.
2+
// http://facebook.github.io/jest/docs/en/webpack.html
3+
4+
module.exports = {
5+
process() {
6+
return 'module.exports = {};'
7+
},
8+
getCacheKey() {
9+
// The output is always the same.
10+
return 'cssTransform'
11+
},
12+
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
const path = require('path')
2+
const camelcase = require('camelcase')
3+
4+
// This is a custom Jest transformer turning file imports into filenames.
5+
// http://facebook.github.io/jest/docs/en/webpack.html
6+
7+
module.exports = {
8+
process(src, filename) {
9+
const assetFilename = JSON.stringify(path.basename(filename))
10+
11+
if (filename.match(/\.svg$/)) {
12+
// Based on how SVGR generates a component name:
13+
// https://github.com/smooth-code/svgr/blob/01b194cf967347d43d4cbe6b434404731b87cf27/packages/core/src/state.js#L6
14+
const pascalCaseFilename = camelcase(path.parse(filename).name, {
15+
pascalCase: true,
16+
})
17+
const componentName = `Svg${pascalCaseFilename}`
18+
return `const React = require('react');
19+
module.exports = {
20+
__esModule: true,
21+
default: ${assetFilename},
22+
ReactComponent: React.forwardRef(function ${componentName}(props, ref) {
23+
return {
24+
$$typeof: Symbol.for('react.element'),
25+
type: 'svg',
26+
ref: ref,
27+
key: null,
28+
props: Object.assign({}, props, {
29+
children: ${assetFilename}
30+
})
31+
};
32+
}),
33+
};`
34+
}
35+
36+
return `module.exports = ${assetFilename};`
37+
},
38+
}

0 commit comments

Comments
 (0)