SIGN IN SIGN UP
facebook / react UNCLAIMED

The library for web and native user interfaces.

244319 0 131 JavaScript
'use strict';
const path = require('path');
const babel = require('@babel/core');
const coffee = require('coffee-script');
const hermesParser = require('hermes-parser');
const tsPreprocessor = require('./typescript/preprocessor');
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const {ReactVersion} = require('../../ReactVersions');
const semver = require('semver');
const pathToBabel = path.join(
require.resolve('@babel/core'),
'../..',
Convert current build system to Rollup and adopt flat bundles (#9327) * WIP * fbjs support * WIP * dev/prod mode WIP * More WIP * builds a cjs bundle * adding forwarding modules * more progress on forwarding modules and FB config * improved how certain modules get inlined for fb and cjs * more forwarding modules * added comments to the module aliasing code * made ReactPerf and ReactTestUtils bundle again * Use -core suffix for all bundles This makes it easier to override things in www. * Add a lazy shim for ReactPerf This prevents a circular dependency between ReactGKJSModule and ReactDOM * Fix forwarding module for ReactCurrentOwner * Revert "Add a lazy shim for ReactPerf" This reverts commit 723b402c07116a70ce8ff1e43a1f4d92052e8f43. * Rename -core suffix to -fb for clarity * Change forwarding modules to import from -fb This is another, more direct fix for ReactPerf circular dependency * should fix fb and cjs bundles for ReactCurrentOwner * added provides module for ReactCurrentOwner * should improve console output * fixed typo with argument passing on functon call * Revert "should improve console output" This breaks the FB bundles. This reverts commit 65f11ee64f678c387cb3cfef9a8b28b89a6272b9. * Work around internal FB transform require() issue * moved ReactInstanceMap out of React and into ReactDOM and ReactDOMFiber * Expose more internal modules to www * Add missing modules to Stack ReactDOM to fix UFI * Fix onlyChild module * improved the build tool * Add a rollup npm script * Rename ReactDOM-fb to ReactDOMStack-fb * Fix circular dependencies now that ReactDOM-fb is a GK switch * Revert "Work around internal FB transform require() issue" This reverts commit 0a50b6a90bffc59f8f5416ef36000b5e3a44d253. * Bump rollup-plugin-commonjs to include a fix for rollup/rollup-plugin-commonjs#176 * Add more forwarding modules that are used on www * Add even more forwarding modules that are used on www * Add DOMProperty to hidden exports * Externalize feature flags This lets www specify them dynamically. * Remove forwarding modules with implementations Instead I'm adding them to react-fb in my diff. * Add all injection necessary for error logging * Add missing forwarding module (oops) * Add ReactART builds * Add ReactDOMServer bundle * Fix UMD build of ReactDOMFiber * Work in progress: start adding ReactNative bundle * tidied up the options for bundles, so they can define what types they output and exclude * Add a working RN build * further improved and tidied up build process * improved how bundles are built by exposing externals and making the process less "magical", also tidied up code and added more comments * better handling of bundling ReactCurrentOwner and accessing it from renderer modules * added NODE_DEV and NODE_PROD * added NPM package creation and copying into build chain * Improved UMD bundles, added better fixture testing and doc plus prod builds * updated internal modules (WIP) * removed all react/lib/* dependencies from appearing in bundles created on build * added react-test-renderer bundles * renamed bundles and paths * fixed fixture path changes * added extract-errors support * added extractErrors warning * moved shims to shims directory in rollup scripts * changed pathing to use build rather than build/rollup * updated release doc to reflect some rollup changes * Updated ReactNative findNodeHandle() to handle number case (#9238) * Add dynamic injection to ReactErrorUtils (#9246) * Fix ReactErrorUtils injection (#9247) * Fix Haste name * Move files around * More descriptive filenames * Add missing ReactErrorUtils shim * Tweak reactComponentExpect to make it standalone-ish in www * Unflowify shims * facebook-www shims now get copied over correctly to build * removed unnecessary resolve * building facebook-www/build is now all sync to prevent IO issues plus handles extra facebook-www src assets * removed react-native-renderer package and made build make a react-native build dir instead * 😭😭😭 * Add more SSR unit tests for elements and children. (#9221) * Adding more SSR unit tests for elements and children. * Some of my SSR tests were testing for react-text and react-empty elements that no longer exist in Fiber. Fixed the tests so that they expect correct markup in Fiber. * Tweaked some test names after @gaearon review comment https://github.com/facebook/react/pull/9221#discussion_r107045673 . Also realized that one of the tests was essentially a direct copy of another, so deleted it. * Responding to code review https://github.com/facebook/react/pull/9221#pullrequestreview-28996315 . Thanks @spicyj! * ReactElementValidator uses temporary ReactNative View propTypes getter (#9256) * Updating packages for 16.0.0-alpha.6 release * Revert "😭😭😭" This reverts commit 7dba33b2cfc67246881f6d57633a80e628ea05ec. * Work around Jest issue with CurrentOwner shared state in www * updated error codes * splits FB into FB_DEV and FB_PROD * Remove deps on specific builds from shims * should no longer mangle FB_PROD output * Added init() dev block to ReactTestUtils * added shims for DEV only code so it does not get included in prod bundles * added a __DEV__ wrapping code to FB_DEV * added __DEV__ flag behind a footer/header * Use right haste names * keeps comments in prod * added external babel helpers plugin * fixed fixtures and updated cjs/umd paths * Fixes Jest so it run tests correctly * fixed an issue with stubbed modules not properly being replaced due to greedy replacement * added a WIP solution for ReactCurrentOwner on FB DEV * adds a FB_TEST bundle * allows both ReactCurrentOwner and react/lib/ReactCurrentOwner * adds -test to provides module name * Remove TEST env * Ensure requires stay at the top * added basic mangle support (disbaled by default) * per bundle property mangling added * moved around plugin order to try and fix deadcode requires as per https://github.com/rollup/rollup/issues/855 * Fix flow issues * removed gulp and grunt and moved tasks to standalone node script * configured circleci to use new paths * Fix lint * removed gulp-extract-errors * added test_build.sh back in * added missing newline to flow.js * fixed test coverage command * changed permissions on test_build.sh * fixed test_html_generations.sh * temp removed html render test * removed the warning output from test_build, the build should do this instead * fixed test_build * fixed broken npm script * Remove unused ViewportMetrics shim * better error output * updated circleci to node 7 for async/await * Fixes * removed coverage test from circleci run * circleci run tets * removed build from circlci * made a dedicated jest script in a new process * moved order around of circlci tasks * changing path to jest in more circleci tests * re-enabled code coverage * Add file header to prod bundles * Remove react-dom/server.js (WIP: decide on the plan) * Only UMD bundles need version header * Merge with master * disabled const evaluation by uglify for <script></script> string literal * deal with ART modules for UMD bundles * improved how bundle output gets printed * fixed filesize difference reporting * added filesize dep * Update yarn lockfile for some reason * now compares against the last run branch built on * added react-dom-server * removed un-needed comment * results only get saved on full builds * moved the rollup sized plugin into a plugins directory * added a missing commonjs() * fixed missing ignore * Hack around to fix RN bundle * Partially fix RN bundles * added react-art bundle and a fixture for it * Point UMD bundle to Fiber and add EventPluginHub to exported internals * Make it build on Node 4 * fixed eslint error with resolve being defined in outer scope * Tweak how build results are calculated and stored * Tweak fixtures build to work on Node 4 * Include LICENSE/PATENTS and fix up package.json files * Add Node bundle for react-test-renderer * Revert "Hack around to fix RN bundle" We'll do this later. This reverts commit 59445a625962d7be4c7c3e98defc8a31f8761ec1. * Revert more RN changes We'll do them separately later * Revert more unintentional changes * Revert changes to error codes * Add accidentally deleted RN externals * added RN_DEV/RN_PROD bundles * fixed typo where RN_DEV and RN_PROD were the wrong way around * Delete/ignore fixture build outputs * Format scripts/ with Prettier * tidied up the Rollup build process and split functions into various different files to improve readability * Copy folder before files * updated yarn.lock * updated results and yarn dependencies to the latest versions
2017-04-05 16:47:29 +01:00
'package.json'
);
const pathToTransformInfiniteLoops = require.resolve(
'../babel/transform-prevent-infinite-loops'
);
Add pragma for feature testing: @gate (#18581) * Add pragma for feature testing: @gate The `@gate` pragma declares under which conditions a test is expected to pass. If the gate condition passes, then the test runs normally (same as if there were no pragma). If the conditional fails, then the test runs and is *expected to fail*. An alternative to `it.experimental` and similar proposals. Examples -------- Basic: ```js // @gate enableBlocksAPI test('passes only if Blocks API is available', () => {/*...*/}) ``` Negation: ```js // @gate !disableLegacyContext test('depends on a deprecated feature', () => {/*...*/}) ``` Multiple flags: ```js // @gate enableNewReconciler // @gate experimental test('needs both useEvent and Blocks', () => {/*...*/}) ``` Logical operators (yes, I'm sorry): ```js // @gate experimental && (enableNewReconciler || disableSchedulerTimeoutBasedOnReactExpirationTime) test('concurrent mode, doesn\'t work in old fork unless Scheduler timeout flag is disabled', () => {/*...*/}) ``` Strings, and comparion operators No use case yet but I figure eventually we'd use this to gate on different release channels: ```js // @gate channel === "experimental" || channel === "modern" test('works in OSS experimental or www modern', () => {/*...*/}) ``` How does it work? I'm guessing those last two examples might be controversial. Supporting those cases did require implementing a mini-parser. The output of the transform is very straightforward, though. Input: ```js // @gate a && (b || c) test('some test', () => {/*...*/}) ``` Output: ```js _test_gate(ctx => ctx.a && (ctx.b || ctx.c, 'some test'), () => {/*...*/}); ``` It also works with `it`, `it.only`, and `fit`. It leaves `it.skip` and `xit` alone because those tests are disabled anyway. `_test_gate` is a global method that I set up in our Jest config. It works about the same as the existing `it.experimental` helper. The context (`ctx`) argument is whatever we want it to be. I set it up so that it throws if you try to access a flag that doesn't exist. I also added some shortcuts for common gating conditions, like `old` and `new`: ```js // @gate experimental test('experimental feature', () => {/*...*/}) // @gate new test('only passes in new reconciler', () => {/*...*/}) ``` Why implement this as a pragma instead of a runtime API? - Doesn't require monkey patching built-in Jest methods. Instead it compiles to a runtime function that composes Jest's API. - Will be easy to upgrade if Jest ever overhauls their API or we switch to a different testing framework (unlikely but who knows). - It feels lightweight so hopefully people won't feel gross using it. For example, adding or removing a gate pragma will never affect the indentation of the test, unlike if you wrapped the test in a conditional block. * Compatibility with console error/warning tracking We patch console.error and console.warning to track unexpected calls in our tests. If there's an unexpected call, we usually throw inside an `afterEach` hook. However, that's too late for tests that we expect to fail, because our `_test_gate` runtime can't capture the error. So I also check for unexpected calls inside `_test_gate`. * Move test flags to dedicated file Added some instructions for how the flags are set up and how to use them. * Add dynamic version of gate API Receives same flags as the pragma. If we ever decide to revert the pragma, we can codemod them to use this instead.
2020-04-13 10:14:34 -07:00
const pathToTransformTestGatePragma = require.resolve(
'../babel/transform-test-gate-pragma'
);
Fix Jest cache for transform-react-version-pragma (#25712) <!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory. Before submitting a pull request, please make sure the following is done: 1. Fork [the repository](https://github.com/facebook/react) and create your branch from `main`. 2. Run `yarn` in the repository root. 3. If you've fixed a bug or added code that should be tested, add tests! 4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch TestName` is helpful in development. 5. Run `yarn test --prod` to test in the production environment. It supports the same options as `yarn test`. 6. If you need a debugger, run `yarn debug-test --watch TestName`, open `chrome://inspect`, and press "Inspect". 7. Format your code with [prettier](https://github.com/prettier/prettier) (`yarn prettier`). 8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only check changed files. 9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`). 10. If you haven't already, complete the CLA. Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html --> ## Summary Jest caching wasn't working correctly for `transform-react-version-pragma`. One condition for including `transform-react-version-pragma` is that `process.env.REACT_VERSION` is set, but it wasn't included in the cache key computation. Thus local test runs would only run without `transform-react-version-pragma`, if jest runs weren't using the `-reactVersion` flag and then added it. Inlined the `scripts/jest/devtools/preprocessor.js` file, because it makes it more obvious that `process.env.REACT_VERSION` is used in `scripts/jest/preprocessor.js` <!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? --> ## How did you test this change? <!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. How exactly did you verify that your PR solves the issue you wanted to solve? If you leave this empty, your PR will very likely be closed. --> Repro step: - Clear jest cache - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental --reactVersion 18.0 - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental Before: Jest cached the first run with `REACT_VERSION` set, so in the second run `transform-react-version-pragma` is still there and runs only the regression tests on old react versions. After: - The second run runs all tests and ignore `// @reactVersion` as expected.
2022-11-28 15:14:34 -08:00
const pathToTransformReactVersionPragma = require.resolve(
'../babel/transform-react-version-pragma'
);
const pathToTransformLazyJSXImport = require.resolve(
'../babel/transform-lazy-jsx-import'
);
const pathToBabelrc = path.join(__dirname, '..', '..', 'babel.config.js');
const pathToErrorCodes = require.resolve('../error-codes/codes.json');
const ReactVersionTestingAgainst = process.env.REACT_VERSION || ReactVersion;
const babelOptions = {
2016-02-26 16:49:32 -08:00
plugins: [
// For Node environment only. For builds, Rollup takes care of ESM.
require.resolve('@babel/plugin-transform-modules-commonjs'),
pathToTransformInfiniteLoops,
Add pragma for feature testing: @gate (#18581) * Add pragma for feature testing: @gate The `@gate` pragma declares under which conditions a test is expected to pass. If the gate condition passes, then the test runs normally (same as if there were no pragma). If the conditional fails, then the test runs and is *expected to fail*. An alternative to `it.experimental` and similar proposals. Examples -------- Basic: ```js // @gate enableBlocksAPI test('passes only if Blocks API is available', () => {/*...*/}) ``` Negation: ```js // @gate !disableLegacyContext test('depends on a deprecated feature', () => {/*...*/}) ``` Multiple flags: ```js // @gate enableNewReconciler // @gate experimental test('needs both useEvent and Blocks', () => {/*...*/}) ``` Logical operators (yes, I'm sorry): ```js // @gate experimental && (enableNewReconciler || disableSchedulerTimeoutBasedOnReactExpirationTime) test('concurrent mode, doesn\'t work in old fork unless Scheduler timeout flag is disabled', () => {/*...*/}) ``` Strings, and comparion operators No use case yet but I figure eventually we'd use this to gate on different release channels: ```js // @gate channel === "experimental" || channel === "modern" test('works in OSS experimental or www modern', () => {/*...*/}) ``` How does it work? I'm guessing those last two examples might be controversial. Supporting those cases did require implementing a mini-parser. The output of the transform is very straightforward, though. Input: ```js // @gate a && (b || c) test('some test', () => {/*...*/}) ``` Output: ```js _test_gate(ctx => ctx.a && (ctx.b || ctx.c, 'some test'), () => {/*...*/}); ``` It also works with `it`, `it.only`, and `fit`. It leaves `it.skip` and `xit` alone because those tests are disabled anyway. `_test_gate` is a global method that I set up in our Jest config. It works about the same as the existing `it.experimental` helper. The context (`ctx`) argument is whatever we want it to be. I set it up so that it throws if you try to access a flag that doesn't exist. I also added some shortcuts for common gating conditions, like `old` and `new`: ```js // @gate experimental test('experimental feature', () => {/*...*/}) // @gate new test('only passes in new reconciler', () => {/*...*/}) ``` Why implement this as a pragma instead of a runtime API? - Doesn't require monkey patching built-in Jest methods. Instead it compiles to a runtime function that composes Jest's API. - Will be easy to upgrade if Jest ever overhauls their API or we switch to a different testing framework (unlikely but who knows). - It feels lightweight so hopefully people won't feel gross using it. For example, adding or removing a gate pragma will never affect the indentation of the test, unlike if you wrapped the test in a conditional block. * Compatibility with console error/warning tracking We patch console.error and console.warning to track unexpected calls in our tests. If there's an unexpected call, we usually throw inside an `afterEach` hook. However, that's too late for tests that we expect to fail, because our `_test_gate` runtime can't capture the error. So I also check for unexpected calls inside `_test_gate`. * Move test flags to dedicated file Added some instructions for how the flags are set up and how to use them. * Add dynamic version of gate API Receives same flags as the pragma. If we ever decide to revert the pragma, we can codemod them to use this instead.
2020-04-13 10:14:34 -07:00
pathToTransformTestGatePragma,
// This optimization is important for extremely performance-sensitive (e.g. React source).
// It's okay to disable it for tests.
[
require.resolve('@babel/plugin-transform-block-scoping'),
{throwIfClosureRequired: false},
],
],
retainLines: true,
};
module.exports = {
process: function (src, filePath) {
Update DevTools to use getCacheForType API (#20548) DevTools was built with a fork of an early idea for how Suspense cache might work. This idea is incompatible with newer APIs like `useTransition` which unfortunately prevented me from making certain UX improvements. This PR swaps out the primary usage of this cache (there are a few) in favor of the newer `unstable_getCacheForType` and `unstable_useCacheRefresh` APIs. We can go back and update the others in follow up PRs. ### Messaging changes I've refactored the way the frontend loads component props/state/etc to hopefully make it better match the Suspense+cache model. Doing this gave up some of the small optimizations I'd added but hopefully the actual performance impact of that is minor and the overall ergonomic improvements of working with the cache API make this worth it. The backend no longer remembers inspected paths. Instead, the frontend sends them every time and the backend sends a response with those paths. I've also added a new "force" parameter that the frontend can use to tell the backend to send a response even if the component hasn't rendered since the last time it asked. (This is used to get data for newly inspected paths.) _Initial inspection..._ ``` front | | back | -- "inspect" (id:1, paths:[], force:true) ---------> | | <------------------------ "inspected" (full-data) -- | ``` _1 second passes with no updates..._ ``` | -- "inspect" (id:1, paths:[], force:false) --------> | | <------------------------ "inspected" (no-change) -- | ``` _User clicks to expand a path, aka hydrate..._ ``` | -- "inspect" (id:1, paths:['foo'], force:true) ----> | | <------------------------ "inspected" (full-data) -- | ``` _1 second passes during which there is an update..._ ``` | -- "inspect" (id:1, paths:['foo'], force:false) ---> | | <----------------- "inspectedElement" (full-data) -- | ``` ### Clear errors/warnings transition Previously this meant there would be a delay after clicking the "clear" button. The UX after this change is much improved. ### Hydrating paths transition I also added a transition to hydration (expanding "dehyrated" paths). ### Better error boundaries I also added a lower-level error boundary in case the new suspense operation ever failed. It provides a better "retry" mechanism (select a new element) so DevTools doesn't become entirely useful. Here I'm intentionally causing an error every time I select an element. ### Improved snapshot tests I also migrated several of the existing snapshot tests to use inline snapshots and added a new serializer for dehydrated props. Inline snapshots are easier to verify and maintain and the new serializer means dehydrated props will be formatted in a way that makes sense rather than being empty (in external snapshots) or super verbose (default inline snapshot format).
2021-01-19 06:51:32 -08:00
if (filePath.match(/\.css$/)) {
// Don't try to parse CSS modules; they aren't needed for tests anyway.
return {code: ''};
Update DevTools to use getCacheForType API (#20548) DevTools was built with a fork of an early idea for how Suspense cache might work. This idea is incompatible with newer APIs like `useTransition` which unfortunately prevented me from making certain UX improvements. This PR swaps out the primary usage of this cache (there are a few) in favor of the newer `unstable_getCacheForType` and `unstable_useCacheRefresh` APIs. We can go back and update the others in follow up PRs. ### Messaging changes I've refactored the way the frontend loads component props/state/etc to hopefully make it better match the Suspense+cache model. Doing this gave up some of the small optimizations I'd added but hopefully the actual performance impact of that is minor and the overall ergonomic improvements of working with the cache API make this worth it. The backend no longer remembers inspected paths. Instead, the frontend sends them every time and the backend sends a response with those paths. I've also added a new "force" parameter that the frontend can use to tell the backend to send a response even if the component hasn't rendered since the last time it asked. (This is used to get data for newly inspected paths.) _Initial inspection..._ ``` front | | back | -- "inspect" (id:1, paths:[], force:true) ---------> | | <------------------------ "inspected" (full-data) -- | ``` _1 second passes with no updates..._ ``` | -- "inspect" (id:1, paths:[], force:false) --------> | | <------------------------ "inspected" (no-change) -- | ``` _User clicks to expand a path, aka hydrate..._ ``` | -- "inspect" (id:1, paths:['foo'], force:true) ----> | | <------------------------ "inspected" (full-data) -- | ``` _1 second passes during which there is an update..._ ``` | -- "inspect" (id:1, paths:['foo'], force:false) ---> | | <----------------- "inspectedElement" (full-data) -- | ``` ### Clear errors/warnings transition Previously this meant there would be a delay after clicking the "clear" button. The UX after this change is much improved. ### Hydrating paths transition I also added a transition to hydration (expanding "dehyrated" paths). ### Better error boundaries I also added a lower-level error boundary in case the new suspense operation ever failed. It provides a better "retry" mechanism (select a new element) so DevTools doesn't become entirely useful. Here I'm intentionally causing an error every time I select an element. ### Improved snapshot tests I also migrated several of the existing snapshot tests to use inline snapshots and added a new serializer for dehydrated props. Inline snapshots are easier to verify and maintain and the new serializer means dehydrated props will be formatted in a way that makes sense rather than being empty (in external snapshots) or super verbose (default inline snapshot format).
2021-01-19 06:51:32 -08:00
}
if (filePath.match(/\.coffee$/)) {
return {code: coffee.compile(src, {bare: true})};
}
if (filePath.match(/\.ts$/) && !filePath.match(/\.d\.ts$/)) {
return {code: tsPreprocessor.compile(src, filePath)};
}
if (filePath.match(/\.json$/)) {
return {code: src};
}
if (!filePath.match(/\/third_party\//)) {
// for test files, we also apply the async-await transform, but we want to
// make sure we don't accidentally apply that transform to product code.
const isTestFile = !!filePath.match(/\/__tests__\//);
const isInDevToolsPackages = !!filePath.match(
/\/packages\/react-devtools.*\//
);
const plugins = [].concat(babelOptions.plugins);
fix[ci]: fixed jest configuration not to skip too many devtools tests (#26955) ## Summary Running `yarn test --project devtools --build` currently skips all non-gated (without `@reactVersion` directives) devtools tests. This is not expected behaviour, these changes are fixing it. There were multiple related PRs to it: - https://github.com/facebook/react/pull/26742 - https://github.com/facebook/react/pull/25712 - https://github.com/facebook/react/pull/24555 With these changes, the resulting behaviour will be: - If `REACT_VERSION` env variable is specified: - jest will not include all non-gated test cases in the test run - jest will run only a specific test case, when specified `REACT_VERSION` value satisfies the range defined by `@reactVersion` directives for this test case - If `REACT_VERSION` env variable is not specified, jest will run all non-gated tests: - jest will include all non-gated test cases in the test run - jest will run all non-gated test cases, the only skipped test cases will be those, which specified the range that does not include the next stable version of react, which will be imported from `ReactVersions.js` ## How did you test this change? Running `profilingCache` test suite without specifying `reactVersion` now skips gated (>= 17 & < 18) test <img width="1447" alt="Screenshot 2023-06-15 at 11 18 22" src="https://github.com/facebook/react/assets/28902667/cad58994-2cb3-44b3-9eb2-1699c01a1eb3"> Running `profilingCache` test suite with specifying `reactVersion` to `17` now runs this test case and skips others correctly <img width="1447" alt="Screenshot 2023-06-15 at 11 20 11" src="https://github.com/facebook/react/assets/28902667/d308960a-c172-4422-ba6f-9c0dbcd6f7d5"> Running `yarn test --project devtools ...` without specifying `reactVersion` now runs all non-gated test cases <img width="398" alt="Screenshot 2023-06-15 at 12 25 12" src="https://github.com/facebook/react/assets/28902667/2b329634-0efd-4c4c-b460-889696bbc9e1"> Running `yarn test --project devtools ...` with specifying `reactVersion` (to `17` in this example) now includes only gated tests <img width="414" alt="Screenshot 2023-06-15 at 12 26 31" src="https://github.com/facebook/react/assets/28902667/a702c27e-4c35-4b12-834c-e5bb06728997">
2023-06-22 09:33:05 +01:00
if (isTestFile && isInDevToolsPackages) {
Fix Jest cache for transform-react-version-pragma (#25712) <!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory. Before submitting a pull request, please make sure the following is done: 1. Fork [the repository](https://github.com/facebook/react) and create your branch from `main`. 2. Run `yarn` in the repository root. 3. If you've fixed a bug or added code that should be tested, add tests! 4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch TestName` is helpful in development. 5. Run `yarn test --prod` to test in the production environment. It supports the same options as `yarn test`. 6. If you need a debugger, run `yarn debug-test --watch TestName`, open `chrome://inspect`, and press "Inspect". 7. Format your code with [prettier](https://github.com/prettier/prettier) (`yarn prettier`). 8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only check changed files. 9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`). 10. If you haven't already, complete the CLA. Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html --> ## Summary Jest caching wasn't working correctly for `transform-react-version-pragma`. One condition for including `transform-react-version-pragma` is that `process.env.REACT_VERSION` is set, but it wasn't included in the cache key computation. Thus local test runs would only run without `transform-react-version-pragma`, if jest runs weren't using the `-reactVersion` flag and then added it. Inlined the `scripts/jest/devtools/preprocessor.js` file, because it makes it more obvious that `process.env.REACT_VERSION` is used in `scripts/jest/preprocessor.js` <!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? --> ## How did you test this change? <!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. How exactly did you verify that your PR solves the issue you wanted to solve? If you leave this empty, your PR will very likely be closed. --> Repro step: - Clear jest cache - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental --reactVersion 18.0 - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental Before: Jest cached the first run with `REACT_VERSION` set, so in the second run `transform-react-version-pragma` is still there and runs only the regression tests on old react versions. After: - The second run runs all tests and ignore `// @reactVersion` as expected.
2022-11-28 15:14:34 -08:00
plugins.push(pathToTransformReactVersionPragma);
}
// This is only for React DevTools tests with React 16.x
// `react/jsx-dev-runtime` and `react/jsx-runtime` are included in the package starting from v17
// Technically 16.14 and 15.7 have the new runtime but we're not testing those versions.
if (
semver.gte(ReactVersionTestingAgainst, '15.0.0') &&
semver.lt(ReactVersionTestingAgainst, '17.0.0')
) {
plugins.push(
[
require.resolve('@babel/plugin-transform-react-jsx'),
{runtime: 'classic'},
],
require.resolve('@babel/plugin-transform-react-jsx-source')
);
} else {
plugins.push([
process.env.NODE_ENV === 'development'
? require.resolve('@babel/plugin-transform-react-jsx-development')
: require.resolve('@babel/plugin-transform-react-jsx'),
// The "automatic" runtime corresponds to react/jsx-runtime. "classic"
// would be React.createElement.
{runtime: 'automatic'},
]);
}
plugins.push(pathToTransformLazyJSXImport);
let sourceAst = hermesParser.parse(src, {babel: true});
return {
code: babel.transformFromAstSync(
sourceAst,
src,
Object.assign(
{filename: path.relative(process.cwd(), filePath)},
babelOptions,
{
plugins,
sourceMaps: process.env.JEST_ENABLE_SOURCE_MAPS
? process.env.JEST_ENABLE_SOURCE_MAPS
: false,
}
)
).code,
};
}
return {code: src};
},
Fix Jest cache for transform-react-version-pragma (#25712) <!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory. Before submitting a pull request, please make sure the following is done: 1. Fork [the repository](https://github.com/facebook/react) and create your branch from `main`. 2. Run `yarn` in the repository root. 3. If you've fixed a bug or added code that should be tested, add tests! 4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch TestName` is helpful in development. 5. Run `yarn test --prod` to test in the production environment. It supports the same options as `yarn test`. 6. If you need a debugger, run `yarn debug-test --watch TestName`, open `chrome://inspect`, and press "Inspect". 7. Format your code with [prettier](https://github.com/prettier/prettier) (`yarn prettier`). 8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only check changed files. 9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`). 10. If you haven't already, complete the CLA. Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html --> ## Summary Jest caching wasn't working correctly for `transform-react-version-pragma`. One condition for including `transform-react-version-pragma` is that `process.env.REACT_VERSION` is set, but it wasn't included in the cache key computation. Thus local test runs would only run without `transform-react-version-pragma`, if jest runs weren't using the `-reactVersion` flag and then added it. Inlined the `scripts/jest/devtools/preprocessor.js` file, because it makes it more obvious that `process.env.REACT_VERSION` is used in `scripts/jest/preprocessor.js` <!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? --> ## How did you test this change? <!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. How exactly did you verify that your PR solves the issue you wanted to solve? If you leave this empty, your PR will very likely be closed. --> Repro step: - Clear jest cache - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental --reactVersion 18.0 - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental Before: Jest cached the first run with `REACT_VERSION` set, so in the second run `transform-react-version-pragma` is still there and runs only the regression tests on old react versions. After: - The second run runs all tests and ignore `// @reactVersion` as expected.
2022-11-28 15:14:34 -08:00
getCacheKey: createCacheKeyFunction(
[
__filename,
pathToBabel,
pathToBabelrc,
pathToTransformInfiniteLoops,
pathToTransformTestGatePragma,
pathToTransformReactVersionPragma,
pathToTransformLazyJSXImport,
Fix Jest cache for transform-react-version-pragma (#25712) <!-- Thanks for submitting a pull request! We appreciate you spending the time to work on these changes. Please provide enough information so that others can review your pull request. The three fields below are mandatory. Before submitting a pull request, please make sure the following is done: 1. Fork [the repository](https://github.com/facebook/react) and create your branch from `main`. 2. Run `yarn` in the repository root. 3. If you've fixed a bug or added code that should be tested, add tests! 4. Ensure the test suite passes (`yarn test`). Tip: `yarn test --watch TestName` is helpful in development. 5. Run `yarn test --prod` to test in the production environment. It supports the same options as `yarn test`. 6. If you need a debugger, run `yarn debug-test --watch TestName`, open `chrome://inspect`, and press "Inspect". 7. Format your code with [prettier](https://github.com/prettier/prettier) (`yarn prettier`). 8. Make sure your code lints (`yarn lint`). Tip: `yarn linc` to only check changed files. 9. Run the [Flow](https://flowtype.org/) type checks (`yarn flow`). 10. If you haven't already, complete the CLA. Learn more about contributing: https://reactjs.org/docs/how-to-contribute.html --> ## Summary Jest caching wasn't working correctly for `transform-react-version-pragma`. One condition for including `transform-react-version-pragma` is that `process.env.REACT_VERSION` is set, but it wasn't included in the cache key computation. Thus local test runs would only run without `transform-react-version-pragma`, if jest runs weren't using the `-reactVersion` flag and then added it. Inlined the `scripts/jest/devtools/preprocessor.js` file, because it makes it more obvious that `process.env.REACT_VERSION` is used in `scripts/jest/preprocessor.js` <!-- Explain the **motivation** for making this change. What existing problem does the pull request solve? --> ## How did you test this change? <!-- Demonstrate the code is solid. Example: The exact commands you ran and their output, screenshots / videos if the pull request changes the user interface. How exactly did you verify that your PR solves the issue you wanted to solve? If you leave this empty, your PR will very likely be closed. --> Repro step: - Clear jest cache - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental --reactVersion 18.0 - node ./scripts/jest/jest-cli.js --build --project devtools --release-channel=experimental Before: Jest cached the first run with `REACT_VERSION` set, so in the second run `transform-react-version-pragma` is still there and runs only the regression tests on old react versions. After: - The second run runs all tests and ignore `// @reactVersion` as expected.
2022-11-28 15:14:34 -08:00
pathToErrorCodes,
],
[
(process.env.REACT_VERSION != null).toString(),
(process.env.NODE_ENV === 'development').toString(),
]
),
};