From 25a8785584c9d54a05887001ee7f498d489a5441 Mon Sep 17 00:00:00 2001 From: Karl Norling Date: Sat, 12 Aug 2023 08:40:25 +0100 Subject: [PATCH 001/101] fix: update `istanbul-lib-instrument` to v6 (#14401) --- CHANGELOG.md | 2 ++ docs/Configuration.md | 1 + packages/jest-reporters/package.json | 2 +- .../version-29.6/Configuration.md | 1 + yarn.lock | 19 ++++++++++++++++--- 5 files changed, 21 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 953ca6b204ca..79c5d914f531 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ### Fixes +- `[jest-reporters]` Update `istanbul-lib-instrument` dependency to v6. ([#14401](https://github.com/jestjs/jest/pull/14401)) + ### Chore & Maintenance ### Performance diff --git a/docs/Configuration.md b/docs/Configuration.md index f60f505bef71..0fe862f4bb3d 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -1177,6 +1177,7 @@ export default config; ``` We hope to support Prettier v3 seamlessly out of the box in a future version of Jest. See [this](https://github.com/jestjs/jest/issues/14305) tracking issue. + ### `projects` \[array<string | ProjectConfig>] diff --git a/packages/jest-reporters/package.json b/packages/jest-reporters/package.json index c9d469cf423d..c38dad8debed 100644 --- a/packages/jest-reporters/package.json +++ b/packages/jest-reporters/package.json @@ -25,7 +25,7 @@ "glob": "^7.1.3", "graceful-fs": "^4.2.9", "istanbul-lib-coverage": "^3.0.0", - "istanbul-lib-instrument": "^5.1.0", + "istanbul-lib-instrument": "^6.0.0", "istanbul-lib-report": "^3.0.0", "istanbul-lib-source-maps": "^4.0.0", "istanbul-reports": "^3.1.3", diff --git a/website/versioned_docs/version-29.6/Configuration.md b/website/versioned_docs/version-29.6/Configuration.md index f60f505bef71..0fe862f4bb3d 100644 --- a/website/versioned_docs/version-29.6/Configuration.md +++ b/website/versioned_docs/version-29.6/Configuration.md @@ -1177,6 +1177,7 @@ export default config; ``` We hope to support Prettier v3 seamlessly out of the box in a future version of Jest. See [this](https://github.com/jestjs/jest/issues/14305) tracking issue. + ### `projects` \[array<string | ProjectConfig>] diff --git a/yarn.lock b/yarn.lock index 1a618ceaeeef..221e78957ae1 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3096,7 +3096,7 @@ __metadata: glob: ^7.1.3 graceful-fs: ^4.2.9 istanbul-lib-coverage: ^3.0.0 - istanbul-lib-instrument: ^5.1.0 + istanbul-lib-instrument: ^6.0.0 istanbul-lib-report: ^3.0.0 istanbul-lib-source-maps: ^4.0.0 istanbul-reports: ^3.1.3 @@ -12251,7 +12251,7 @@ __metadata: languageName: node linkType: hard -"istanbul-lib-instrument@npm:^5.0.4, istanbul-lib-instrument@npm:^5.1.0": +"istanbul-lib-instrument@npm:^5.0.4": version: 5.2.1 resolution: "istanbul-lib-instrument@npm:5.2.1" dependencies: @@ -12264,6 +12264,19 @@ __metadata: languageName: node linkType: hard +"istanbul-lib-instrument@npm:^6.0.0": + version: 6.0.0 + resolution: "istanbul-lib-instrument@npm:6.0.0" + dependencies: + "@babel/core": ^7.12.3 + "@babel/parser": ^7.14.7 + "@istanbuljs/schema": ^0.1.2 + istanbul-lib-coverage: ^3.2.0 + semver: ^7.5.4 + checksum: b9dc3723a769e65dbe1b912f935088ffc07cf393fa78a3ce79022c91aabb0ad01405ffd56083cdd822e514798e9daae3ea7bfe85633b094ecb335d28eb0a3f97 + languageName: node + linkType: hard + "istanbul-lib-report@npm:^3.0.0": version: 3.0.0 resolution: "istanbul-lib-report@npm:3.0.0" @@ -18193,7 +18206,7 @@ __metadata: languageName: node linkType: hard -"semver@npm:^7.0.0, semver@npm:^7.1.1, semver@npm:^7.3.2, semver@npm:^7.3.4, semver@npm:^7.3.5, semver@npm:^7.3.7, semver@npm:^7.3.8, semver@npm:^7.5.1, semver@npm:^7.5.3, semver@npm:~7.5.4": +"semver@npm:^7.0.0, semver@npm:^7.1.1, semver@npm:^7.3.2, semver@npm:^7.3.4, semver@npm:^7.3.5, semver@npm:^7.3.7, semver@npm:^7.3.8, semver@npm:^7.5.1, semver@npm:^7.5.3, semver@npm:^7.5.4, semver@npm:~7.5.4": version: 7.5.4 resolution: "semver@npm:7.5.4" dependencies: From 49bacb9620b87c476bd5ba1b30e26ca2c4f42a70 Mon Sep 17 00:00:00 2001 From: Frazer Smith Date: Tue, 15 Aug 2023 14:00:44 +0100 Subject: [PATCH 002/101] chore: update jest repo organisation in urls (#14413) --- .eslintrc.cjs | 2 +- .github/ISSUE_TEMPLATE.md | 2 +- .github/ISSUE_TEMPLATE/bug.yml | 2 +- CONTRIBUTING.md | 4 +-- README.md | 20 +++++++------- constraints.pro | 2 +- docs/CodeTransformation.md | 4 +-- docs/Configuration.md | 26 +++++++++---------- docs/ECMAScriptModules.md | 4 +-- docs/ExpectAPI.md | 2 +- docs/GlobalAPI.md | 10 +++---- docs/JestObjectAPI.md | 2 +- docs/JestPlatform.md | 10 +++---- docs/ManualMocks.md | 2 +- docs/MoreResources.md | 2 +- docs/Puppeteer.md | 2 +- docs/SnapshotTesting.md | 12 ++++----- docs/Troubleshooting.md | 4 +-- docs/TutorialAsync.md | 2 +- docs/TutorialReact.md | 4 +-- docs/TutorialReactNative.md | 2 +- docs/TutorialjQuery.md | 2 +- docs/UpgradingToJest29.md | 2 +- docs/WatchPlugins.md | 2 +- e2e/__tests__/console.test.ts | 2 +- e2e/__tests__/dependencyClash.test.ts | 2 +- e2e/__tests__/toMatchInlineSnapshot.test.ts | 2 +- e2e/snapshot/__tests__/snapshot.test.js | 2 +- .../testSequencer.js | 2 +- packages/babel-jest/README.md | 2 +- packages/babel-jest/package.json | 2 +- packages/babel-plugin-jest-hoist/README.md | 2 +- packages/babel-plugin-jest-hoist/package.json | 2 +- packages/babel-preset-jest/README.md | 2 +- packages/babel-preset-jest/package.json | 2 +- packages/diff-sequences/package.json | 2 +- packages/expect-utils/package.json | 2 +- packages/expect-utils/src/utils.ts | 2 +- packages/expect/package.json | 2 +- .../expect/src/__tests__/toEqual-dom.test.ts | 2 +- packages/jest-changed-files/package.json | 2 +- packages/jest-circus/README.md | 2 +- packages/jest-circus/package.json | 2 +- packages/jest-cli/package.json | 4 +-- packages/jest-config/package.json | 2 +- packages/jest-console/package.json | 2 +- packages/jest-console/src/BufferedConsole.ts | 2 +- packages/jest-console/src/CustomConsole.ts | 2 +- packages/jest-core/package.json | 4 +-- .../jest-core/src/__tests__/watch.test.js | 2 +- packages/jest-core/src/collectHandles.ts | 2 +- packages/jest-core/src/testSchedulerHelper.ts | 2 +- .../package.json | 2 +- packages/jest-diff/package.json | 2 +- packages/jest-docblock/package.json | 2 +- packages/jest-each/README.md | 2 +- packages/jest-each/package.json | 2 +- packages/jest-environment-jsdom/package.json | 2 +- packages/jest-environment-node/package.json | 2 +- packages/jest-environment/package.json | 2 +- packages/jest-expect/package.json | 2 +- packages/jest-fake-timers/package.json | 2 +- .../jest-fake-timers/src/legacyFakeTimers.ts | 2 +- packages/jest-get-type/package.json | 2 +- packages/jest-globals/package.json | 2 +- packages/jest-haste-map/package.json | 2 +- packages/jest-haste-map/src/crawlers/node.ts | 2 +- packages/jest-haste-map/src/index.ts | 4 +-- .../lib/__tests__/dependencyExtractor.test.js | 2 +- packages/jest-jasmine2/package.json | 2 +- packages/jest-leak-detector/package.json | 2 +- packages/jest-matcher-utils/README.md | 2 +- packages/jest-matcher-utils/package.json | 2 +- packages/jest-message-util/package.json | 2 +- packages/jest-message-util/src/index.ts | 2 +- packages/jest-mock/package.json | 2 +- packages/jest-phabricator/package.json | 2 +- packages/jest-regex-util/package.json | 2 +- packages/jest-repl/package.json | 2 +- packages/jest-reporters/package.json | 4 +-- .../jest-reporters/src/CoverageReporter.ts | 2 +- .../src/GitHubActionsReporter.ts | 2 +- .../jest-reporters/src/VerboseReporter.ts | 2 +- .../jest-resolve-dependencies/package.json | 2 +- packages/jest-resolve/package.json | 2 +- packages/jest-runner/package.json | 2 +- packages/jest-runtime/package.json | 2 +- packages/jest-schemas/package.json | 2 +- packages/jest-snapshot/package.json | 2 +- packages/jest-source-map/package.json | 2 +- packages/jest-test-result/package.json | 2 +- packages/jest-test-sequencer/package.json | 2 +- packages/jest-transform/package.json | 2 +- .../jest-transform/src/ScriptTransformer.ts | 2 +- packages/jest-types/package.json | 2 +- packages/jest-util/package.json | 2 +- packages/jest-util/src/createProcessObject.ts | 2 +- packages/jest-validate/package.json | 2 +- packages/jest-watcher/package.json | 4 +-- packages/jest-worker/README.md | 2 +- packages/jest-worker/package.json | 2 +- packages/jest-worker/src/types.ts | 2 +- .../workers/__tests__/WorkerEdgeCases.test.ts | 2 +- packages/jest/package.json | 2 +- packages/pretty-format/package.json | 2 +- website/README.md | 2 +- ...-11-javascript-unit-testing-performance.md | 2 +- website/blog/2016-04-12-jest-11.md | 6 ++--- website/blog/2016-06-22-jest-13.md | 2 +- website/blog/2016-07-27-jest-14.md | 12 ++++----- website/blog/2016-09-01-jest-15.md | 10 +++---- website/blog/2016-10-03-jest-16.md | 2 +- website/blog/2016-12-15-2016-in-jest.md | 12 ++++----- ...2017-01-30-a-great-developer-experience.md | 2 +- ...e-watch-mode-test-platform-improvements.md | 20 +++++++------- ...delightful-testing-multi-project-runner.md | 4 +-- website/blog/2017-12-18-jest-22.md | 8 +++--- ...jest-23-blazing-fast-delightful-testing.md | 4 +-- ...refreshing-polished-typescript-friendly.md | 26 +++++++++---------- website/blog/2020-01-21-jest-25.md | 16 ++++++------ website/blog/2020-05-05-jest-26.md | 22 ++++++++-------- .../blog/2021-03-09-jest-website-upgrade.md | 2 +- website/blog/2021-05-25-jest-27.md | 22 ++++++++-------- website/blog/2022-04-25-jest-28.md | 4 +-- website/blog/2022-08-25-jest-29.md | 2 +- website/docusaurus.config.js | 8 +++--- website/src/pages/help.js | 2 +- website/src/pages/index.js | 4 +-- website/src/pages/versions.js | 4 +-- website/static/_redirects | 2 +- website/users.json | 2 +- .../version-25.x/Configuration.md | 24 ++++++++--------- .../version-25.x/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-25.x/ExpectAPI.md | 2 +- .../version-25.x/JestObjectAPI.md | 2 +- .../version-25.x/JestPlatform.md | 10 +++---- .../version-25.x/ManualMocks.md | 2 +- .../version-25.x/MockFunctionAPI.md | 2 +- .../version-25.x/MoreResources.md | 2 +- .../versioned_docs/version-25.x/Puppeteer.md | 2 +- .../version-25.x/SnapshotTesting.md | 12 ++++----- .../versioned_docs/version-25.x/TimerMocks.md | 2 +- .../version-25.x/Troubleshooting.md | 4 +-- .../version-25.x/TutorialAsync.md | 2 +- .../version-25.x/TutorialReact.md | 4 +-- .../version-25.x/TutorialReactNative.md | 2 +- .../version-25.x/TutorialjQuery.md | 2 +- .../version-25.x/WatchPlugins.md | 2 +- .../version-26.x/Configuration.md | 24 ++++++++--------- .../version-26.x/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-26.x/ExpectAPI.md | 2 +- .../versioned_docs/version-26.x/GlobalAPI.md | 2 +- .../version-26.x/JestObjectAPI.md | 2 +- .../version-26.x/JestPlatform.md | 10 +++---- .../version-26.x/ManualMocks.md | 2 +- .../version-26.x/MockFunctionAPI.md | 2 +- .../version-26.x/MoreResources.md | 2 +- .../versioned_docs/version-26.x/Puppeteer.md | 2 +- .../version-26.x/SnapshotTesting.md | 12 ++++----- .../versioned_docs/version-26.x/TimerMocks.md | 2 +- .../version-26.x/Troubleshooting.md | 4 +-- .../version-26.x/TutorialAsync.md | 2 +- .../version-26.x/TutorialReact.md | 4 +-- .../version-26.x/TutorialReactNative.md | 2 +- .../version-26.x/TutorialjQuery.md | 2 +- .../version-26.x/WatchPlugins.md | 2 +- .../version-27.x/CodeTransformation.md | 2 +- .../version-27.x/Configuration.md | 24 ++++++++--------- .../version-27.x/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-27.x/ExpectAPI.md | 2 +- .../versioned_docs/version-27.x/GlobalAPI.md | 2 +- .../version-27.x/JestObjectAPI.md | 2 +- .../version-27.x/JestPlatform.md | 10 +++---- .../version-27.x/ManualMocks.md | 2 +- .../version-27.x/MockFunctionAPI.md | 2 +- .../version-27.x/MoreResources.md | 2 +- .../versioned_docs/version-27.x/Puppeteer.md | 2 +- .../version-27.x/SnapshotTesting.md | 12 ++++----- .../versioned_docs/version-27.x/TimerMocks.md | 2 +- .../version-27.x/Troubleshooting.md | 4 +-- .../version-27.x/TutorialAsync.md | 2 +- .../version-27.x/TutorialReact.md | 4 +-- .../version-27.x/TutorialReactNative.md | 2 +- .../version-27.x/TutorialjQuery.md | 2 +- .../version-27.x/WatchPlugins.md | 2 +- .../version-28.x/CodeTransformation.md | 4 +-- .../version-28.x/Configuration.md | 22 ++++++++-------- .../version-28.x/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-28.x/ExpectAPI.md | 2 +- .../versioned_docs/version-28.x/GlobalAPI.md | 8 +++--- .../version-28.x/JestObjectAPI.md | 2 +- .../version-28.x/JestPlatform.md | 10 +++---- .../version-28.x/ManualMocks.md | 2 +- .../version-28.x/MoreResources.md | 2 +- .../versioned_docs/version-28.x/Puppeteer.md | 2 +- .../version-28.x/SnapshotTesting.md | 12 ++++----- .../version-28.x/Troubleshooting.md | 4 +-- .../version-28.x/TutorialAsync.md | 2 +- .../version-28.x/TutorialReact.md | 4 +-- .../version-28.x/TutorialReactNative.md | 2 +- .../version-28.x/TutorialjQuery.md | 2 +- .../version-28.x/UpgradingToJest28.md | 4 +-- .../version-28.x/WatchPlugins.md | 2 +- .../version-29.0/CodeTransformation.md | 4 +-- .../version-29.0/Configuration.md | 26 +++++++++---------- .../version-29.0/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.0/ExpectAPI.md | 2 +- .../versioned_docs/version-29.0/GlobalAPI.md | 10 +++---- .../version-29.0/JestObjectAPI.md | 2 +- .../version-29.0/JestPlatform.md | 10 +++---- .../version-29.0/ManualMocks.md | 2 +- .../version-29.0/MoreResources.md | 2 +- .../versioned_docs/version-29.0/Puppeteer.md | 2 +- .../version-29.0/SnapshotTesting.md | 12 ++++----- .../version-29.0/Troubleshooting.md | 4 +-- .../version-29.0/TutorialAsync.md | 2 +- .../version-29.0/TutorialReact.md | 4 +-- .../version-29.0/TutorialReactNative.md | 2 +- .../version-29.0/TutorialjQuery.md | 2 +- .../version-29.0/UpgradingToJest29.md | 2 +- .../version-29.0/WatchPlugins.md | 2 +- .../version-29.1/CodeTransformation.md | 4 +-- .../version-29.1/Configuration.md | 26 +++++++++---------- .../version-29.1/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.1/ExpectAPI.md | 2 +- .../versioned_docs/version-29.1/GlobalAPI.md | 10 +++---- .../version-29.1/JestObjectAPI.md | 2 +- .../version-29.1/JestPlatform.md | 10 +++---- .../version-29.1/ManualMocks.md | 2 +- .../version-29.1/MoreResources.md | 2 +- .../versioned_docs/version-29.1/Puppeteer.md | 2 +- .../version-29.1/SnapshotTesting.md | 12 ++++----- .../version-29.1/Troubleshooting.md | 4 +-- .../version-29.1/TutorialAsync.md | 2 +- .../version-29.1/TutorialReact.md | 4 +-- .../version-29.1/TutorialReactNative.md | 2 +- .../version-29.1/TutorialjQuery.md | 2 +- .../version-29.1/UpgradingToJest29.md | 2 +- .../version-29.1/WatchPlugins.md | 2 +- .../version-29.2/CodeTransformation.md | 4 +-- .../version-29.2/Configuration.md | 24 ++++++++--------- .../version-29.2/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.2/ExpectAPI.md | 2 +- .../versioned_docs/version-29.2/GlobalAPI.md | 10 +++---- .../version-29.2/JestObjectAPI.md | 2 +- .../version-29.2/JestPlatform.md | 10 +++---- .../version-29.2/ManualMocks.md | 2 +- .../version-29.2/MoreResources.md | 2 +- .../versioned_docs/version-29.2/Puppeteer.md | 2 +- .../version-29.2/SnapshotTesting.md | 12 ++++----- .../version-29.2/Troubleshooting.md | 4 +-- .../version-29.2/TutorialAsync.md | 2 +- .../version-29.2/TutorialReact.md | 4 +-- .../version-29.2/TutorialReactNative.md | 2 +- .../version-29.2/TutorialjQuery.md | 2 +- .../version-29.2/UpgradingToJest29.md | 2 +- .../version-29.2/WatchPlugins.md | 2 +- .../version-29.3/CodeTransformation.md | 4 +-- .../version-29.3/Configuration.md | 26 +++++++++---------- .../version-29.3/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.3/ExpectAPI.md | 2 +- .../versioned_docs/version-29.3/GlobalAPI.md | 10 +++---- .../version-29.3/JestObjectAPI.md | 2 +- .../version-29.3/JestPlatform.md | 10 +++---- .../version-29.3/ManualMocks.md | 2 +- .../version-29.3/MoreResources.md | 2 +- .../versioned_docs/version-29.3/Puppeteer.md | 2 +- .../version-29.3/SnapshotTesting.md | 12 ++++----- .../version-29.3/Troubleshooting.md | 4 +-- .../version-29.3/TutorialAsync.md | 2 +- .../version-29.3/TutorialReact.md | 4 +-- .../version-29.3/TutorialReactNative.md | 2 +- .../version-29.3/TutorialjQuery.md | 2 +- .../version-29.3/UpgradingToJest29.md | 2 +- .../version-29.3/WatchPlugins.md | 2 +- .../version-29.4/CodeTransformation.md | 4 +-- .../version-29.4/Configuration.md | 26 +++++++++---------- .../version-29.4/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.4/ExpectAPI.md | 2 +- .../versioned_docs/version-29.4/GlobalAPI.md | 10 +++---- .../version-29.4/JestObjectAPI.md | 2 +- .../version-29.4/JestPlatform.md | 10 +++---- .../version-29.4/ManualMocks.md | 2 +- .../version-29.4/MoreResources.md | 2 +- .../versioned_docs/version-29.4/Puppeteer.md | 2 +- .../version-29.4/SnapshotTesting.md | 12 ++++----- .../version-29.4/Troubleshooting.md | 4 +-- .../version-29.4/TutorialAsync.md | 2 +- .../version-29.4/TutorialReact.md | 4 +-- .../version-29.4/TutorialReactNative.md | 2 +- .../version-29.4/TutorialjQuery.md | 2 +- .../version-29.4/UpgradingToJest29.md | 2 +- .../version-29.4/WatchPlugins.md | 2 +- .../version-29.5/CodeTransformation.md | 4 +-- .../version-29.5/Configuration.md | 26 +++++++++---------- .../version-29.5/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.5/ExpectAPI.md | 2 +- .../versioned_docs/version-29.5/GlobalAPI.md | 10 +++---- .../version-29.5/JestObjectAPI.md | 2 +- .../version-29.5/JestPlatform.md | 10 +++---- .../version-29.5/ManualMocks.md | 2 +- .../version-29.5/MoreResources.md | 2 +- .../versioned_docs/version-29.5/Puppeteer.md | 2 +- .../version-29.5/SnapshotTesting.md | 12 ++++----- .../version-29.5/Troubleshooting.md | 4 +-- .../version-29.5/TutorialAsync.md | 2 +- .../version-29.5/TutorialReact.md | 4 +-- .../version-29.5/TutorialReactNative.md | 2 +- .../version-29.5/TutorialjQuery.md | 2 +- .../version-29.5/UpgradingToJest29.md | 2 +- .../version-29.5/WatchPlugins.md | 2 +- .../version-29.6/CodeTransformation.md | 4 +-- .../version-29.6/Configuration.md | 26 +++++++++---------- .../version-29.6/ECMAScriptModules.md | 4 +-- .../versioned_docs/version-29.6/ExpectAPI.md | 2 +- .../versioned_docs/version-29.6/GlobalAPI.md | 10 +++---- .../version-29.6/JestObjectAPI.md | 2 +- .../version-29.6/JestPlatform.md | 10 +++---- .../version-29.6/ManualMocks.md | 2 +- .../version-29.6/MoreResources.md | 2 +- .../versioned_docs/version-29.6/Puppeteer.md | 2 +- .../version-29.6/SnapshotTesting.md | 12 ++++----- .../version-29.6/Troubleshooting.md | 4 +-- .../version-29.6/TutorialAsync.md | 2 +- .../version-29.6/TutorialReact.md | 4 +-- .../version-29.6/TutorialReactNative.md | 2 +- .../version-29.6/TutorialjQuery.md | 2 +- .../version-29.6/UpgradingToJest29.md | 2 +- .../version-29.6/WatchPlugins.md | 2 +- 329 files changed, 746 insertions(+), 746 deletions(-) diff --git a/.eslintrc.cjs b/.eslintrc.cjs index d2f6e0f5d60a..089863ba5f5e 100644 --- a/.eslintrc.cjs +++ b/.eslintrc.cjs @@ -128,7 +128,7 @@ module.exports = { rules: { '@typescript-eslint/ban-types': [ 'error', - // TODO: remove these overrides: https://github.com/facebook/jest/issues/10177 + // TODO: remove these overrides: https://github.com/jestjs/jest/issues/10177 {types: {Function: false, object: false, '{}': false}}, ], 'local/ban-types-eventually': [ diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 8b0483e22ec9..62a266204106 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,4 +1,4 @@ -## 👉 [Please follow one of these issue templates](https://github.com/facebook/jest/issues/new/choose) 👈 +## 👉 [Please follow one of these issue templates](https://github.com/jestjs/jest/issues/new/choose) 👈 diff --git a/.github/ISSUE_TEMPLATE/bug.yml b/.github/ISSUE_TEMPLATE/bug.yml index 60128a50d325..a208081cbdb7 100644 --- a/.github/ISSUE_TEMPLATE/bug.yml +++ b/.github/ISSUE_TEMPLATE/bug.yml @@ -41,7 +41,7 @@ body: label: Version description: | The version of Jest you are using. - Is it the [latest](https://github.com/facebook/jest/releases)? Test and see if the bug has already been fixed. + Is it the [latest](https://github.com/jestjs/jest/releases)? Test and see if the bug has already been fixed. placeholder: ex. 27.0.6 validations: required: true diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 68902505e39f..2e018e5fc568 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,7 +2,7 @@ Jest is one of Facebook's open-source projects that is both under very active development and is also being used to ship code to everybody on [Facebook.com](https://www.facebook.com). We're still working out the kinks to make contributing to this project as easy and transparent as possible, but we're not quite there yet. Hopefully, this document makes the process for contributing clear and answers some questions that you may have. -If you want an already configured online IDE to contribute to Jest, you can use [Gitpod](https://gitpod.io/#https://github.com/facebook/jest)! +If you want an already configured online IDE to contribute to Jest, you can use [Gitpod](https://gitpod.io/#https://github.com/jestjs/jest)! ## [Code of Conduct](https://code.facebook.com/codeofconduct) @@ -131,7 +131,7 @@ Ran all test suites. ## Checking Constraints -We use [Yarn Constraints](https://yarnpkg.com/features/constraints) to enforce various rules across the repository. They are declared inside the [`constraints.pro` file](https://github.com/facebook/jest/blob/main/constraints.pro) and their purposes are documented with comments. +We use [Yarn Constraints](https://yarnpkg.com/features/constraints) to enforce various rules across the repository. They are declared inside the [`constraints.pro` file](https://github.com/jestjs/jest/blob/main/constraints.pro) and their purposes are documented with comments. Constraints can be checked with `yarn constraints`, and fixed with `yarn constraints --fix`. Generally speaking: diff --git a/README.md b/README.md index b7e005413c95..ba462358a145 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ npm version - + Jest is released under the MIT license. @@ -10,11 +10,11 @@

- GitHub CI Status + GitHub CI Status Coverage Status

- Gitpod ready-to-code + Gitpod ready-to-code

@@ -229,13 +229,13 @@ Learn more about using [Jest on the official site!](https://jestjs.io) ## Badge -Show the world you're using _Jest_ `→` [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) [![jest tested](https://img.shields.io/badge/Jest-tested-eee.svg?logo=jest&labelColor=99424f)](https://github.com/facebook/jest) [![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/facebook/jest) +Show the world you're using _Jest_ `→` [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/jestjs/jest) [![jest tested](https://img.shields.io/badge/Jest-tested-eee.svg?logo=jest&labelColor=99424f)](https://github.com/jestjs/jest) [![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/jestjs/jest) ```md -[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg?logo=jest)](https://github.com/facebook/jest) -[![jest tested](https://img.shields.io/badge/Jest-tested-eee.svg?logo=jest&labelColor=99424f)](https://github.com/facebook/jest) -[![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/facebook/jest) +[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg?logo=jest)](https://github.com/jestjs/jest) +[![jest tested](https://img.shields.io/badge/Jest-tested-eee.svg?logo=jest&labelColor=99424f)](https://github.com/jestjs/jest) +[![jest](https://jestjs.io/img/jest-badge.svg)](https://github.com/jestjs/jest) ``` ## Contributing @@ -250,15 +250,15 @@ Facebook has adopted a Code of Conduct that we expect project participants to ad Read our [contributing guide](CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Jest. -### [Good First Issues](https://github.com/facebook/jest/labels/good%20first%20issue) +### [Good First Issues](https://github.com/jestjs/jest/labels/good%20first%20issue) -To help you get your feet wet and get you familiar with our contribution process, we have a list of [good first issues](https://github.com/facebook/jest/labels/good%20first%20issue) that contain bugs which have a relatively limited scope. This is a great place to get started. +To help you get your feet wet and get you familiar with our contribution process, we have a list of [good first issues](https://github.com/jestjs/jest/labels/good%20first%20issue) that contain bugs which have a relatively limited scope. This is a great place to get started. ## Credits This project exists thanks to all the people who [contribute](CONTRIBUTING.md). - + ### [Backers](https://opencollective.com/jest#backer) diff --git a/constraints.pro b/constraints.pro index b9179863ccfb..e0f1abbe277e 100644 --- a/constraints.pro +++ b/constraints.pro @@ -43,7 +43,7 @@ gen_enforced_field(WorkspaceCwd, 'license', null) :- % Enforces the repository field for all public workspaces while removing it from private workspaces gen_enforced_field(WorkspaceCwd, 'repository.type', 'git') :- \+ workspace_field(WorkspaceCwd, 'private', true). -gen_enforced_field(WorkspaceCwd, 'repository.url', 'https://github.com/facebook/jest.git') :- +gen_enforced_field(WorkspaceCwd, 'repository.url', 'https://github.com/jestjs/jest.git') :- \+ workspace_field(WorkspaceCwd, 'private', true). gen_enforced_field(WorkspaceCwd, 'repository.directory', WorkspaceCwd) :- \+ workspace_field(WorkspaceCwd, 'private', true). diff --git a/docs/CodeTransformation.md b/docs/CodeTransformation.md index d2a568fcb024..14d96a16f649 100644 --- a/docs/CodeTransformation.md +++ b/docs/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/docs/Configuration.md b/docs/Configuration.md index 0fe862f4bb3d..4e23e314b103 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -1401,7 +1401,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1583,7 +1583,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1837,7 +1837,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1860,9 +1860,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2149,7 +2149,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2189,7 +2189,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2231,7 +2231,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2446,7 +2446,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2464,7 +2464,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/docs/ECMAScriptModules.md b/docs/ECMAScriptModules.md index 1aa9a39b0c68..feaed6bdb961 100644 --- a/docs/ECMAScriptModules.md +++ b/docs/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -48,7 +48,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index d140e0dd4340..46b2c361585e 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -1591,7 +1591,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/docs/GlobalAPI.md b/docs/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index d3811b628b86..130e6d7768a2 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -1071,7 +1071,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/docs/JestPlatform.md b/docs/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/docs/JestPlatform.md +++ b/docs/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/docs/ManualMocks.md +++ b/docs/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/docs/MoreResources.md b/docs/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/docs/MoreResources.md +++ b/docs/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/docs/Puppeteer.md b/docs/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/docs/Puppeteer.md +++ b/docs/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/docs/SnapshotTesting.md b/docs/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/docs/SnapshotTesting.md +++ b/docs/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/docs/TutorialAsync.md b/docs/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/docs/TutorialAsync.md +++ b/docs/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/docs/TutorialReact.md b/docs/TutorialReact.md index 13165b1b4e95..fd6f7620acce 100644 --- a/docs/TutorialReact.md +++ b/docs/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). ### Custom transformers diff --git a/docs/TutorialReactNative.md b/docs/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/docs/TutorialReactNative.md +++ b/docs/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/docs/TutorialjQuery.md b/docs/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/docs/TutorialjQuery.md +++ b/docs/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/docs/UpgradingToJest29.md b/docs/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/docs/UpgradingToJest29.md +++ b/docs/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/docs/WatchPlugins.md b/docs/WatchPlugins.md index acb66e0a8673..57ddeaec07e4 100644 --- a/docs/WatchPlugins.md +++ b/docs/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/e2e/__tests__/console.test.ts b/e2e/__tests__/console.test.ts index 163f612ed3a1..051f30e2e86d 100644 --- a/e2e/__tests__/console.test.ts +++ b/e2e/__tests__/console.test.ts @@ -82,7 +82,7 @@ test('respects noStackTrace in config', () => { expect(summary).toMatchSnapshot(); }); -// issue: https://github.com/facebook/jest/issues/5223 +// issue: https://github.com/jestjs/jest/issues/5223 test('the jsdom console is the same as the test console', () => { const {stderr, stdout, exitCode} = runJest('console-jsdom'); const {summary, rest} = extractSummary(stderr); diff --git a/e2e/__tests__/dependencyClash.test.ts b/e2e/__tests__/dependencyClash.test.ts index 311c89453d4d..4783514805f0 100644 --- a/e2e/__tests__/dependencyClash.test.ts +++ b/e2e/__tests__/dependencyClash.test.ts @@ -25,7 +25,7 @@ beforeEach(() => { // `invariant` package from npm and `invariant.js` that provides `invariant` // module we can still require the right invariant. This is pretty specific // use case and in the future we should probably delete this test. -// see: https://github.com/facebook/jest/pull/6687 +// see: https://github.com/jestjs/jest/pull/6687 test('does not require project modules from inside node_modules', () => { writeFiles(tempDir, { '__tests__/test.js': ` diff --git a/e2e/__tests__/toMatchInlineSnapshot.test.ts b/e2e/__tests__/toMatchInlineSnapshot.test.ts index 483fe0ab904a..446609348377 100644 --- a/e2e/__tests__/toMatchInlineSnapshot.test.ts +++ b/e2e/__tests__/toMatchInlineSnapshot.test.ts @@ -249,7 +249,7 @@ test('writes snapshots with non-literals in expect(...)', () => { expect(fileAfter).toMatchSnapshot(); }); -// issue: https://github.com/facebook/jest/issues/6702 +// issue: https://github.com/jestjs/jest/issues/6702 test('handles mocking native modules prettier relies on', () => { const filename = 'mockFail.test.js'; const test = ` diff --git a/e2e/snapshot/__tests__/snapshot.test.js b/e2e/snapshot/__tests__/snapshot.test.js index 3947650b5b36..428adb059667 100644 --- a/e2e/snapshot/__tests__/snapshot.test.js +++ b/e2e/snapshot/__tests__/snapshot.test.js @@ -34,7 +34,7 @@ describe('snapshot', () => { ); }); - // Issue reported here: https://github.com/facebook/jest/issues/2969 + // Issue reported here: https://github.com/jestjs/jest/issues/2969 it('works with \\r\\n', () => { expect('
\r\n
').toMatchSnapshot(); }); diff --git a/e2e/worker-restart-before-send/testSequencer.js b/e2e/worker-restart-before-send/testSequencer.js index e5a470ed49fe..a5e9b5d43ed5 100644 --- a/e2e/worker-restart-before-send/testSequencer.js +++ b/e2e/worker-restart-before-send/testSequencer.js @@ -13,7 +13,7 @@ const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } diff --git a/packages/babel-jest/README.md b/packages/babel-jest/README.md index 95050196b2a0..8716cc13c818 100644 --- a/packages/babel-jest/README.md +++ b/packages/babel-jest/README.md @@ -1,6 +1,6 @@ # babel-jest -[Babel](https://github.com/babel/babel) [jest](https://github.com/facebook/jest) plugin +[Babel](https://github.com/babel/babel) [jest](https://github.com/jestjs/jest) plugin ## Usage diff --git a/packages/babel-jest/package.json b/packages/babel-jest/package.json index 71d8b7e14381..27bda5279438 100644 --- a/packages/babel-jest/package.json +++ b/packages/babel-jest/package.json @@ -4,7 +4,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/babel-jest" }, "license": "MIT", diff --git a/packages/babel-plugin-jest-hoist/README.md b/packages/babel-plugin-jest-hoist/README.md index 1a90bbe8b165..7c1421bb27f1 100644 --- a/packages/babel-plugin-jest-hoist/README.md +++ b/packages/babel-plugin-jest-hoist/README.md @@ -1,6 +1,6 @@ # babel-plugin-jest-hoist -Babel plugin to hoist `jest.disableAutomock`, `jest.enableAutomock`, `jest.unmock`, `jest.mock`, calls above `import` statements. This plugin is automatically included when using [babel-jest](https://github.com/facebook/jest/tree/main/packages/babel-jest). +Babel plugin to hoist `jest.disableAutomock`, `jest.enableAutomock`, `jest.unmock`, `jest.mock`, calls above `import` statements. This plugin is automatically included when using [babel-jest](https://github.com/jestjs/jest/tree/main/packages/babel-jest). ## Installation diff --git a/packages/babel-plugin-jest-hoist/package.json b/packages/babel-plugin-jest-hoist/package.json index 3698c80ff7a9..d56194756057 100644 --- a/packages/babel-plugin-jest-hoist/package.json +++ b/packages/babel-plugin-jest-hoist/package.json @@ -3,7 +3,7 @@ "version": "29.5.0", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/babel-plugin-jest-hoist" }, "engines": { diff --git a/packages/babel-preset-jest/README.md b/packages/babel-preset-jest/README.md index 4457c086cece..745e1b031072 100644 --- a/packages/babel-preset-jest/README.md +++ b/packages/babel-preset-jest/README.md @@ -1,6 +1,6 @@ # babel-preset-jest -> Babel preset for all Jest plugins. This preset is automatically included when using [babel-jest](https://github.com/facebook/jest/tree/main/packages/babel-jest). +> Babel preset for all Jest plugins. This preset is automatically included when using [babel-jest](https://github.com/jestjs/jest/tree/main/packages/babel-jest). ## Install diff --git a/packages/babel-preset-jest/package.json b/packages/babel-preset-jest/package.json index 735fd90b35f1..4d664eca8cd4 100644 --- a/packages/babel-preset-jest/package.json +++ b/packages/babel-preset-jest/package.json @@ -3,7 +3,7 @@ "version": "29.5.0", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/babel-preset-jest" }, "license": "MIT", diff --git a/packages/diff-sequences/package.json b/packages/diff-sequences/package.json index ee91b067bbdc..4ba131b9da33 100644 --- a/packages/diff-sequences/package.json +++ b/packages/diff-sequences/package.json @@ -3,7 +3,7 @@ "version": "29.4.3", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/diff-sequences" }, "license": "MIT", diff --git a/packages/expect-utils/package.json b/packages/expect-utils/package.json index 2487565b4252..7aa8251bb7ee 100644 --- a/packages/expect-utils/package.json +++ b/packages/expect-utils/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/expect-utils" }, "license": "MIT", diff --git a/packages/expect-utils/src/utils.ts b/packages/expect-utils/src/utils.ts index 62c3085a56fa..cb4ab7fda33f 100644 --- a/packages/expect-utils/src/utils.ts +++ b/packages/expect-utils/src/utils.ts @@ -377,7 +377,7 @@ export const typeEquality = (a: any, b: any): boolean | undefined => { // Since Jest globals are different from Node globals, // constructors are different even between arrays when comparing properties of mock objects. // Both of them should be able to compare correctly when they are array-to-array. - // https://github.com/facebook/jest/issues/2549 + // https://github.com/jestjs/jest/issues/2549 (Array.isArray(a) && Array.isArray(b)) ) { return undefined; diff --git a/packages/expect/package.json b/packages/expect/package.json index 08b75c77559d..8882f53f5002 100644 --- a/packages/expect/package.json +++ b/packages/expect/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/expect" }, "license": "MIT", diff --git a/packages/expect/src/__tests__/toEqual-dom.test.ts b/packages/expect/src/__tests__/toEqual-dom.test.ts index 2dc5c8b3110b..09270754f54d 100644 --- a/packages/expect/src/__tests__/toEqual-dom.test.ts +++ b/packages/expect/src/__tests__/toEqual-dom.test.ts @@ -15,7 +15,7 @@ import {expect} from '@jest/globals'; describe('toEqual', () => { describe('duck type', () => { - // https://github.com/facebook/jest/issues/7786 + // https://github.com/jestjs/jest/issues/7786 const createElement = (name: string, ...childNodes: Array) => ({ childNodes, diff --git a/packages/jest-changed-files/package.json b/packages/jest-changed-files/package.json index 866a23a3992e..a0a5c5cd1e25 100644 --- a/packages/jest-changed-files/package.json +++ b/packages/jest-changed-files/package.json @@ -3,7 +3,7 @@ "version": "29.5.0", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-changed-files" }, "license": "MIT", diff --git a/packages/jest-circus/README.md b/packages/jest-circus/README.md index 75a2f771d23d..6c5c68363388 100644 --- a/packages/jest-circus/README.md +++ b/packages/jest-circus/README.md @@ -1,4 +1,4 @@ -[type-definitions]: https://github.com/facebook/jest/blob/main/packages/jest-types/src/Circus.ts +[type-definitions]: https://github.com/jestjs/jest/blob/main/packages/jest-types/src/Circus.ts

diff --git a/packages/jest-circus/package.json b/packages/jest-circus/package.json index 89305b99ad15..9e9253fe952a 100644 --- a/packages/jest-circus/package.json +++ b/packages/jest-circus/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-circus" }, "license": "MIT", diff --git a/packages/jest-cli/package.json b/packages/jest-cli/package.json index bb0532334f73..684aa0f981df 100644 --- a/packages/jest-cli/package.json +++ b/packages/jest-cli/package.json @@ -50,11 +50,11 @@ }, "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-cli" }, "bugs": { - "url": "https://github.com/facebook/jest/issues" + "url": "https://github.com/jestjs/jest/issues" }, "homepage": "https://jestjs.io/", "license": "MIT", diff --git a/packages/jest-config/package.json b/packages/jest-config/package.json index 6630d1a2b47a..2ac8f06dfabd 100644 --- a/packages/jest-config/package.json +++ b/packages/jest-config/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-config" }, "license": "MIT", diff --git a/packages/jest-console/package.json b/packages/jest-console/package.json index 5155e9157a81..bd69334c0be5 100644 --- a/packages/jest-console/package.json +++ b/packages/jest-console/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-console" }, "license": "MIT", diff --git a/packages/jest-console/src/BufferedConsole.ts b/packages/jest-console/src/BufferedConsole.ts index b91117bf36e6..526d51c38fdf 100644 --- a/packages/jest-console/src/BufferedConsole.ts +++ b/packages/jest-console/src/BufferedConsole.ts @@ -79,7 +79,7 @@ export default class BufferedConsole extends Console { if (!(error instanceof AssertionError)) { throw error; } - // https://github.com/facebook/jest/pull/13422#issuecomment-1273396392 + // https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392 this._log('assert', error.toString().replace(/:\n\n.*\n/gs, '')); } } diff --git a/packages/jest-console/src/CustomConsole.ts b/packages/jest-console/src/CustomConsole.ts index 04b23c023553..451971604e55 100644 --- a/packages/jest-console/src/CustomConsole.ts +++ b/packages/jest-console/src/CustomConsole.ts @@ -56,7 +56,7 @@ export default class CustomConsole extends Console { if (!(error instanceof AssertionError)) { throw error; } - // https://github.com/facebook/jest/pull/13422#issuecomment-1273396392 + // https://github.com/jestjs/jest/pull/13422#issuecomment-1273396392 this._logError('assert', error.toString().replace(/:\n\n.*\n/gs, '')); } } diff --git a/packages/jest-core/package.json b/packages/jest-core/package.json index 93eac1eff68b..7c6989e582dc 100644 --- a/packages/jest-core/package.json +++ b/packages/jest-core/package.json @@ -61,11 +61,11 @@ }, "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-core" }, "bugs": { - "url": "https://github.com/facebook/jest/issues" + "url": "https://github.com/jestjs/jest/issues" }, "homepage": "https://jestjs.io/", "license": "MIT", diff --git a/packages/jest-core/src/__tests__/watch.test.js b/packages/jest-core/src/__tests__/watch.test.js index 7f412e1561a3..8bd334bd91a4 100644 --- a/packages/jest-core/src/__tests__/watch.test.js +++ b/packages/jest-core/src/__tests__/watch.test.js @@ -446,7 +446,7 @@ describe('Watch mode flows', () => { ); // The jury's still out on 'a', 'c', 'f', 'o', 'w' and '?'… - // See https://github.com/facebook/jest/issues/6693 + // See https://github.com/jestjs/jest/issues/6693 it.each` key | plugin ${'t'} | ${'TestNamePattern'} diff --git a/packages/jest-core/src/collectHandles.ts b/packages/jest-core/src/collectHandles.ts index a88d58ffdbdd..3a9172fd18f1 100644 --- a/packages/jest-core/src/collectHandles.ts +++ b/packages/jest-core/src/collectHandles.ts @@ -145,7 +145,7 @@ export default function collectHandles(): HandleCollectionResult { if (activeHandles.size > 0) { // For some special objects such as `TLSWRAP`. - // Ref: https://github.com/facebook/jest/issues/11665 + // Ref: https://github.com/jestjs/jest/issues/11665 runGC(); await asyncSleep(0); diff --git a/packages/jest-core/src/testSchedulerHelper.ts b/packages/jest-core/src/testSchedulerHelper.ts index 6582415ac5d5..79c7a056ee95 100644 --- a/packages/jest-core/src/testSchedulerHelper.ts +++ b/packages/jest-core/src/testSchedulerHelper.ts @@ -41,7 +41,7 @@ export function shouldRunInBand( * quickly we also run in band to reduce the overhead of spawning workers. * Finally, the user can provide the runInBand argument in the CLI to * force running in band, which sets maxWorkers to 1 here: - * https://github.com/facebook/jest/blob/d106643a8ee0ffa9c2f11c6bb2d12094e99135aa/packages/jest-config/src/getMaxWorkers.ts#L27-L28 + * https://github.com/jestjs/jest/blob/d106643a8ee0ffa9c2f11c6bb2d12094e99135aa/packages/jest-config/src/getMaxWorkers.ts#L27-L28 */ const areFastTests = timings.every(timing => timing < SLOW_TEST_TIME); const oneWorkerOrLess = maxWorkers <= 1; diff --git a/packages/jest-create-cache-key-function/package.json b/packages/jest-create-cache-key-function/package.json index ec1e7a883304..4446994ec170 100644 --- a/packages/jest-create-cache-key-function/package.json +++ b/packages/jest-create-cache-key-function/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-create-cache-key-function" }, "dependencies": { diff --git a/packages/jest-diff/package.json b/packages/jest-diff/package.json index c79474c9eb32..6488ec8e3df3 100644 --- a/packages/jest-diff/package.json +++ b/packages/jest-diff/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-diff" }, "license": "MIT", diff --git a/packages/jest-docblock/package.json b/packages/jest-docblock/package.json index 421c0c5d361f..df23f9d258ef 100644 --- a/packages/jest-docblock/package.json +++ b/packages/jest-docblock/package.json @@ -3,7 +3,7 @@ "version": "29.4.3", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-docblock" }, "license": "MIT", diff --git a/packages/jest-each/README.md b/packages/jest-each/README.md index da3b2adb9e4a..3b4384387ca4 100644 --- a/packages/jest-each/README.md +++ b/packages/jest-each/README.md @@ -5,7 +5,7 @@
-[![version](https://img.shields.io/npm/v/jest-each.svg?style=flat-square)](https://www.npmjs.com/package/jest-each) [![downloads](https://img.shields.io/npm/dm/jest-each.svg?style=flat-square)](http://npm-stat.com/charts.html?package=jest-each&from=2017-03-21) [![MIT License](https://img.shields.io/npm/l/jest-each.svg?style=flat-square)](https://github.com/facebook/jest/blob/main/LICENSE) +[![version](https://img.shields.io/npm/v/jest-each.svg?style=flat-square)](https://www.npmjs.com/package/jest-each) [![downloads](https://img.shields.io/npm/dm/jest-each.svg?style=flat-square)](http://npm-stat.com/charts.html?package=jest-each&from=2017-03-21) [![MIT License](https://img.shields.io/npm/l/jest-each.svg?style=flat-square)](https://github.com/jestjs/jest/blob/main/LICENSE) A parameterised testing library for [Jest](https://jestjs.io/) inspired by [mocha-each](https://github.com/ryym/mocha-each). diff --git a/packages/jest-each/package.json b/packages/jest-each/package.json index 0e3480c0a304..1005558319de 100644 --- a/packages/jest-each/package.json +++ b/packages/jest-each/package.json @@ -13,7 +13,7 @@ }, "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-each" }, "keywords": [ diff --git a/packages/jest-environment-jsdom/package.json b/packages/jest-environment-jsdom/package.json index c6beacb6fe96..2060256623af 100644 --- a/packages/jest-environment-jsdom/package.json +++ b/packages/jest-environment-jsdom/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-environment-jsdom" }, "license": "MIT", diff --git a/packages/jest-environment-node/package.json b/packages/jest-environment-node/package.json index 90678c040ee5..304ecf582529 100644 --- a/packages/jest-environment-node/package.json +++ b/packages/jest-environment-node/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-environment-node" }, "license": "MIT", diff --git a/packages/jest-environment/package.json b/packages/jest-environment/package.json index 7c87e934f280..a8c104f47811 100644 --- a/packages/jest-environment/package.json +++ b/packages/jest-environment/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-environment" }, "license": "MIT", diff --git a/packages/jest-expect/package.json b/packages/jest-expect/package.json index 237e497cd777..578f6ca43c98 100644 --- a/packages/jest-expect/package.json +++ b/packages/jest-expect/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-expect" }, "license": "MIT", diff --git a/packages/jest-fake-timers/package.json b/packages/jest-fake-timers/package.json index 4a37d2511827..eea6721c0826 100644 --- a/packages/jest-fake-timers/package.json +++ b/packages/jest-fake-timers/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-fake-timers" }, "license": "MIT", diff --git a/packages/jest-fake-timers/src/legacyFakeTimers.ts b/packages/jest-fake-timers/src/legacyFakeTimers.ts index f04e12083b8a..e4e05fec7618 100644 --- a/packages/jest-fake-timers/src/legacyFakeTimers.ts +++ b/packages/jest-fake-timers/src/legacyFakeTimers.ts @@ -244,7 +244,7 @@ export default class FakeTimers { runOnlyPendingTimers(): void { // We need to hold the current shape of `this._timers` because existing // timers can add new ones to the map and hence would run more than necessary. - // See https://github.com/facebook/jest/pull/4608 for details + // See https://github.com/jestjs/jest/pull/4608 for details const timerEntries = Array.from(this._timers.entries()); this._checkFakeTimers(); this._immediates.forEach(this._runImmediate, this); diff --git a/packages/jest-get-type/package.json b/packages/jest-get-type/package.json index 97222a4016bc..5463bac7458d 100644 --- a/packages/jest-get-type/package.json +++ b/packages/jest-get-type/package.json @@ -4,7 +4,7 @@ "version": "29.4.3", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-get-type" }, "engines": { diff --git a/packages/jest-globals/package.json b/packages/jest-globals/package.json index 815c3add9ed8..39797cfa07a3 100644 --- a/packages/jest-globals/package.json +++ b/packages/jest-globals/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-globals" }, "engines": { diff --git a/packages/jest-haste-map/package.json b/packages/jest-haste-map/package.json index 1a4319a1e719..b6964dae1346 100644 --- a/packages/jest-haste-map/package.json +++ b/packages/jest-haste-map/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-haste-map" }, "license": "MIT", diff --git a/packages/jest-haste-map/src/crawlers/node.ts b/packages/jest-haste-map/src/crawlers/node.ts index 014fef8a1a25..8555eeb7b415 100644 --- a/packages/jest-haste-map/src/crawlers/node.ts +++ b/packages/jest-haste-map/src/crawlers/node.ts @@ -162,7 +162,7 @@ function findNative( let stdout = ''; if (child.stdout === null) { throw new Error( - 'stdout is null - this should never happen. Please open up an issue at https://github.com/facebook/jest', + 'stdout is null - this should never happen. Please open up an issue at https://github.com/jestjs/jest', ); } child.stdout.setEncoding('utf-8'); diff --git a/packages/jest-haste-map/src/index.ts b/packages/jest-haste-map/src/index.ts index bc65149445bf..5012d6ef1af5 100644 --- a/packages/jest-haste-map/src/index.ts +++ b/packages/jest-haste-map/src/index.ts @@ -46,9 +46,9 @@ import type { WorkerMetadata, } from './types'; import {FSEventsWatcher} from './watchers/FSEventsWatcher'; -// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/10919 +// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/jestjs/jest/pull/10919 import NodeWatcher from './watchers/NodeWatcher'; -// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/facebook/jest/pull/5387 +// @ts-expect-error: not converted to TypeScript - it's a fork: https://github.com/jestjs/jest/pull/5387 import WatchmanWatcher from './watchers/WatchmanWatcher'; import {getSha1, worker} from './worker'; // TypeScript doesn't like us importing from outside `rootDir`, but it doesn't diff --git a/packages/jest-haste-map/src/lib/__tests__/dependencyExtractor.test.js b/packages/jest-haste-map/src/lib/__tests__/dependencyExtractor.test.js index 2fe56e4ce67d..d07cb7b5187b 100644 --- a/packages/jest-haste-map/src/lib/__tests__/dependencyExtractor.test.js +++ b/packages/jest-haste-map/src/lib/__tests__/dependencyExtractor.test.js @@ -70,7 +70,7 @@ describe('dependencyExtractor', () => { ); }); - // https://github.com/facebook/jest/issues/8547 + // https://github.com/jestjs/jest/issues/8547 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#Import_a_module_for_its_side_effects_only it('should extract dependencies from side-effect only `import` statements', () => { const code = ` diff --git a/packages/jest-jasmine2/package.json b/packages/jest-jasmine2/package.json index d95864779f9c..0953e9a2679a 100644 --- a/packages/jest-jasmine2/package.json +++ b/packages/jest-jasmine2/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-jasmine2" }, "license": "MIT", diff --git a/packages/jest-leak-detector/package.json b/packages/jest-leak-detector/package.json index e39523ba29b1..5cea240be6ef 100644 --- a/packages/jest-leak-detector/package.json +++ b/packages/jest-leak-detector/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-leak-detector" }, "license": "MIT", diff --git a/packages/jest-matcher-utils/README.md b/packages/jest-matcher-utils/README.md index d3e9d13bf849..17e19c2bca92 100644 --- a/packages/jest-matcher-utils/README.md +++ b/packages/jest-matcher-utils/README.md @@ -9,7 +9,7 @@ To add this package as a dependency of a project, run either of the following co - `npm install jest-matcher-utils` - `yarn add jest-matcher-utils` -## Exports ([src/index.ts](https://github.com/facebook/jest/blob/HEAD/packages/jest-matcher-utils/src/index.ts)) +## Exports ([src/index.ts](https://github.com/jestjs/jest/blob/HEAD/packages/jest-matcher-utils/src/index.ts)) ### Functions diff --git a/packages/jest-matcher-utils/package.json b/packages/jest-matcher-utils/package.json index 1f948f2f9e01..0dcf8a3bd94e 100644 --- a/packages/jest-matcher-utils/package.json +++ b/packages/jest-matcher-utils/package.json @@ -4,7 +4,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-matcher-utils" }, "engines": { diff --git a/packages/jest-message-util/package.json b/packages/jest-message-util/package.json index 408630ed3e31..8a713cfd61ba 100644 --- a/packages/jest-message-util/package.json +++ b/packages/jest-message-util/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-message-util" }, "engines": { diff --git a/packages/jest-message-util/src/index.ts b/packages/jest-message-util/src/index.ts index 37078cbc842b..9455f9b4fb0f 100644 --- a/packages/jest-message-util/src/index.ts +++ b/packages/jest-message-util/src/index.ts @@ -355,7 +355,7 @@ export const formatStackTrace = ( let fileContent; try { // TODO: check & read HasteFS instead of reading the filesystem: - // see: https://github.com/facebook/jest/pull/5405#discussion_r164281696 + // see: https://github.com/jestjs/jest/pull/5405#discussion_r164281696 fileContent = fs.readFileSync(filename, 'utf8'); renderedCallsite = getRenderedCallsite(fileContent, line, column); } catch { diff --git a/packages/jest-mock/package.json b/packages/jest-mock/package.json index f8442e28c493..d161044f93d5 100644 --- a/packages/jest-mock/package.json +++ b/packages/jest-mock/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-mock" }, "license": "MIT", diff --git a/packages/jest-phabricator/package.json b/packages/jest-phabricator/package.json index 439813195aff..02ff6570875b 100644 --- a/packages/jest-phabricator/package.json +++ b/packages/jest-phabricator/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-phabricator" }, "types": "./build/index.d.ts", diff --git a/packages/jest-regex-util/package.json b/packages/jest-regex-util/package.json index e35fe605cb9d..a947a4eb09eb 100644 --- a/packages/jest-regex-util/package.json +++ b/packages/jest-regex-util/package.json @@ -3,7 +3,7 @@ "version": "29.4.3", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-regex-util" }, "devDependencies": { diff --git a/packages/jest-repl/package.json b/packages/jest-repl/package.json index 703d4c717224..bcdb54472c2a 100644 --- a/packages/jest-repl/package.json +++ b/packages/jest-repl/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-repl" }, "license": "MIT", diff --git a/packages/jest-reporters/package.json b/packages/jest-reporters/package.json index c38dad8debed..db659285d78d 100644 --- a/packages/jest-reporters/package.json +++ b/packages/jest-reporters/package.json @@ -67,11 +67,11 @@ }, "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-reporters" }, "bugs": { - "url": "https://github.com/facebook/jest/issues" + "url": "https://github.com/jestjs/jest/issues" }, "homepage": "https://jestjs.io/", "license": "MIT", diff --git a/packages/jest-reporters/src/CoverageReporter.ts b/packages/jest-reporters/src/CoverageReporter.ts index 84aefc822803..953c4ed4be51 100644 --- a/packages/jest-reporters/src/CoverageReporter.ts +++ b/packages/jest-reporters/src/CoverageReporter.ts @@ -274,7 +274,7 @@ export default class CoverageReporter extends BaseReporter { Array<[string, string]> >((agg, thresholdGroup) => { // Preserve trailing slash, but not required if root dir - // See https://github.com/facebook/jest/issues/12703 + // See https://github.com/jestjs/jest/issues/12703 const resolvedThresholdGroup = path.resolve(thresholdGroup); const suffix = (thresholdGroup.endsWith(path.sep) || diff --git a/packages/jest-reporters/src/GitHubActionsReporter.ts b/packages/jest-reporters/src/GitHubActionsReporter.ts index df9640214742..b5024068cdf2 100644 --- a/packages/jest-reporters/src/GitHubActionsReporter.ts +++ b/packages/jest-reporters/src/GitHubActionsReporter.ts @@ -161,7 +161,7 @@ export default class GitHubActionsReporter extends BaseReporter { return true; } else { throw new Error( - `Sum(${computedTotal}) of passed (${passedTestSuites}) and failed (${failedTestSuites}) test suites is greater than the total number of test suites (${totalTestSuites}). Please report the bug at https://github.com/facebook/jest/issues`, + `Sum(${computedTotal}) of passed (${passedTestSuites}) and failed (${failedTestSuites}) test suites is greater than the total number of test suites (${totalTestSuites}). Please report the bug at https://github.com/jestjs/jest/issues`, ); } } diff --git a/packages/jest-reporters/src/VerboseReporter.ts b/packages/jest-reporters/src/VerboseReporter.ts index 03dfb6ff3f95..46ae16d6a4b1 100644 --- a/packages/jest-reporters/src/VerboseReporter.ts +++ b/packages/jest-reporters/src/VerboseReporter.ts @@ -30,7 +30,7 @@ export default class VerboseReporter extends DefaultReporter { } // Verbose mode is for debugging. Buffering of output is undesirable. - // See https://github.com/facebook/jest/issues/8208 + // See https://github.com/jestjs/jest/issues/8208 protected override __wrapStdio( stream: NodeJS.WritableStream | NodeJS.WriteStream, ): void { diff --git a/packages/jest-resolve-dependencies/package.json b/packages/jest-resolve-dependencies/package.json index ca7977d75d0e..1fa24663d173 100644 --- a/packages/jest-resolve-dependencies/package.json +++ b/packages/jest-resolve-dependencies/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-resolve-dependencies" }, "license": "MIT", diff --git a/packages/jest-resolve/package.json b/packages/jest-resolve/package.json index e52ed10a7866..c3e450021874 100644 --- a/packages/jest-resolve/package.json +++ b/packages/jest-resolve/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-resolve" }, "license": "MIT", diff --git a/packages/jest-runner/package.json b/packages/jest-runner/package.json index 263a69c2b6d9..1c519464bd50 100644 --- a/packages/jest-runner/package.json +++ b/packages/jest-runner/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-runner" }, "license": "MIT", diff --git a/packages/jest-runtime/package.json b/packages/jest-runtime/package.json index 11ea2d47a71d..48daf4f01b4c 100644 --- a/packages/jest-runtime/package.json +++ b/packages/jest-runtime/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-runtime" }, "license": "MIT", diff --git a/packages/jest-schemas/package.json b/packages/jest-schemas/package.json index 11fe033bda2d..75fcf613723c 100644 --- a/packages/jest-schemas/package.json +++ b/packages/jest-schemas/package.json @@ -3,7 +3,7 @@ "version": "29.6.0", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-schemas" }, "license": "MIT", diff --git a/packages/jest-snapshot/package.json b/packages/jest-snapshot/package.json index 385a2bcb24c0..dfd8b9c6bb2f 100644 --- a/packages/jest-snapshot/package.json +++ b/packages/jest-snapshot/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-snapshot" }, "license": "MIT", diff --git a/packages/jest-source-map/package.json b/packages/jest-source-map/package.json index 91dd9629a19e..3f046969c8e0 100644 --- a/packages/jest-source-map/package.json +++ b/packages/jest-source-map/package.json @@ -3,7 +3,7 @@ "version": "29.6.0", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-source-map" }, "license": "MIT", diff --git a/packages/jest-test-result/package.json b/packages/jest-test-result/package.json index 2fdb26147a46..a442b5538daf 100644 --- a/packages/jest-test-result/package.json +++ b/packages/jest-test-result/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-test-result" }, "license": "MIT", diff --git a/packages/jest-test-sequencer/package.json b/packages/jest-test-sequencer/package.json index 60aacc26dba5..5b222e3eb514 100644 --- a/packages/jest-test-sequencer/package.json +++ b/packages/jest-test-sequencer/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-test-sequencer" }, "license": "MIT", diff --git a/packages/jest-transform/package.json b/packages/jest-transform/package.json index 98d514debf6b..3888bf8acfee 100644 --- a/packages/jest-transform/package.json +++ b/packages/jest-transform/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-transform" }, "license": "MIT", diff --git a/packages/jest-transform/src/ScriptTransformer.ts b/packages/jest-transform/src/ScriptTransformer.ts index a73015488b07..6728407dfcb9 100644 --- a/packages/jest-transform/src/ScriptTransformer.ts +++ b/packages/jest-transform/src/ScriptTransformer.ts @@ -411,7 +411,7 @@ class ScriptTransformer { if (transformed.map == null || transformed.map === '') { try { //Could be a potential freeze here. - //See: https://github.com/facebook/jest/pull/5177#discussion_r158883570 + //See: https://github.com/jestjs/jest/pull/5177#discussion_r158883570 const inlineSourceMap = sourcemapFromSource(transformed.code); if (inlineSourceMap) { transformed.map = inlineSourceMap.toObject() as FixedRawSourceMap; diff --git a/packages/jest-types/package.json b/packages/jest-types/package.json index c2d647296408..bb8bdf35ddbc 100644 --- a/packages/jest-types/package.json +++ b/packages/jest-types/package.json @@ -3,7 +3,7 @@ "version": "29.6.1", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-types" }, "engines": { diff --git a/packages/jest-util/package.json b/packages/jest-util/package.json index ff043991ddd8..e166a053e16f 100644 --- a/packages/jest-util/package.json +++ b/packages/jest-util/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-util" }, "license": "MIT", diff --git a/packages/jest-util/src/createProcessObject.ts b/packages/jest-util/src/createProcessObject.ts index 1cb8b26d7614..252b121275be 100644 --- a/packages/jest-util/src/createProcessObject.ts +++ b/packages/jest-util/src/createProcessObject.ts @@ -92,7 +92,7 @@ export default function createProcessObject(): NodeJS.Process { } catch (e: any) { // Make sure it's actually set instead of potentially ignoring errors if (newProcess[Symbol.toStringTag] !== 'process') { - e.message = `Unable to set toStringTag on process. Please open up an issue at https://github.com/facebook/jest\n\n${e.message}`; + e.message = `Unable to set toStringTag on process. Please open up an issue at https://github.com/jestjs/jest\n\n${e.message}`; throw e; } diff --git a/packages/jest-validate/package.json b/packages/jest-validate/package.json index b3a178c1f7b5..cdc9667feb73 100644 --- a/packages/jest-validate/package.json +++ b/packages/jest-validate/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-validate" }, "license": "MIT", diff --git a/packages/jest-watcher/package.json b/packages/jest-watcher/package.json index 500b635be96a..fc98d2cc20ae 100644 --- a/packages/jest-watcher/package.json +++ b/packages/jest-watcher/package.json @@ -23,11 +23,11 @@ }, "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-watcher" }, "bugs": { - "url": "https://github.com/facebook/jest/issues" + "url": "https://github.com/jestjs/jest/issues" }, "engines": { "node": "^14.15.0 || ^16.10.0 || >=18.0.0" diff --git a/packages/jest-worker/README.md b/packages/jest-worker/README.md index bf14f9fe7e5d..f9e1131c95e7 100644 --- a/packages/jest-worker/README.md +++ b/packages/jest-worker/README.md @@ -77,7 +77,7 @@ Allow customizing all options passed to `child_process.fork`. By default, some v #### `idleMemoryLimit: number` (optional) -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a task the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. If no limit is set this process does not occur. The limit can be specified in 2 ways: diff --git a/packages/jest-worker/package.json b/packages/jest-worker/package.json index 4a87d8a9a37b..034700d8c76c 100644 --- a/packages/jest-worker/package.json +++ b/packages/jest-worker/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest-worker" }, "license": "MIT", diff --git a/packages/jest-worker/src/types.ts b/packages/jest-worker/src/types.ts index dbd1f2b430a1..9d0e45a172ab 100644 --- a/packages/jest-worker/src/types.ts +++ b/packages/jest-worker/src/types.ts @@ -178,7 +178,7 @@ export type WorkerOptions = { idleMemoryLimit?: number; /** * This mainly exists so the path can be changed during testing. - * https://github.com/facebook/jest/issues/9543 + * https://github.com/jestjs/jest/issues/9543 */ childWorkerPath?: string; /** diff --git a/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.ts b/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.ts index 50ea9daf40af..3b283cc9c925 100644 --- a/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.ts +++ b/packages/jest-worker/src/workers/__tests__/WorkerEdgeCases.test.ts @@ -413,7 +413,7 @@ describe.each([ }); }); - // Regression test for https://github.com/facebook/jest/issues/13183 + // Regression test for https://github.com/jestjs/jest/issues/13183 test('onEnd callback is called', async () => { let onEndPromiseResolve: () => void; let onEndPromiseReject: (err: Error) => void; diff --git a/packages/jest/package.json b/packages/jest/package.json index 5997ffbe0fbc..49b28053d5b3 100644 --- a/packages/jest/package.json +++ b/packages/jest/package.json @@ -36,7 +36,7 @@ }, "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/jest" }, "homepage": "https://jestjs.io/", diff --git a/packages/pretty-format/package.json b/packages/pretty-format/package.json index 7834250963b2..788d1e3b1a71 100644 --- a/packages/pretty-format/package.json +++ b/packages/pretty-format/package.json @@ -3,7 +3,7 @@ "version": "29.6.2", "repository": { "type": "git", - "url": "https://github.com/facebook/jest.git", + "url": "https://github.com/jestjs/jest.git", "directory": "packages/pretty-format" }, "license": "MIT", diff --git a/website/README.md b/website/README.md index 2508657003cd..008dc10d9bab 100644 --- a/website/README.md +++ b/website/README.md @@ -44,4 +44,4 @@ An older Docusaurus v1 site exist for versions <= 25.x: - Netlify site: https://app.netlify.com/sites/jest-archive - Url: https://archive.jestjs.io -- GitHub branch: https://github.com/facebook/jest/tree/jest-website-v1 +- GitHub branch: https://github.com/jestjs/jest/tree/jest-website-v1 diff --git a/website/blog/2016-03-11-javascript-unit-testing-performance.md b/website/blog/2016-03-11-javascript-unit-testing-performance.md index 706dc9a642c8..1baa53b30c39 100644 --- a/website/blog/2016-03-11-javascript-unit-testing-performance.md +++ b/website/blog/2016-03-11-javascript-unit-testing-performance.md @@ -114,6 +114,6 @@ A lot of the above changes improved the test runtime by 10% or sometimes even 50 More importantly, adding new tests causes total runtime to grow very slowly. Engineers can write and run more tests without feeling the costs. -With Jest's recent 0.9 release and performance improvements from the [node-haste2 integration](https://github.com/facebook/jest/pull/599), the runtime of the [Relay](https://github.com/facebook/relay) framework's test suite went down from 60 seconds to about 25 and the [react-native](https://github.com/facebook/react-native) test suite now finishes in less than ten seconds on a 13” MacBook Pro. +With Jest's recent 0.9 release and performance improvements from the [node-haste2 integration](https://github.com/jestjs/jest/pull/599), the runtime of the [Relay](https://github.com/facebook/relay) framework's test suite went down from 60 seconds to about 25 and the [react-native](https://github.com/facebook/react-native) test suite now finishes in less than ten seconds on a 13” MacBook Pro. We're very happy with the wins we've seen so far, and we're going to keep working on Jest and making it better. If you are curious about contributing to Jest, feel free get in touch on GitHub, [Discord](https://discord.gg/j6FKKQQrW9) or Facebook :) diff --git a/website/blog/2016-04-12-jest-11.md b/website/blog/2016-04-12-jest-11.md index 230e5f32c7ac..8a2be7f94663 100644 --- a/website/blog/2016-04-12-jest-11.md +++ b/website/blog/2016-04-12-jest-11.md @@ -13,7 +13,7 @@ If you are using Jest 0.9 or Jest 0.10 the upgrade should be seamless. All chang #### Babel Integration and Simplified Setup -`babel-jest` was adopted within the newly modularized Jest [repository](https://github.com/facebook/jest/tree/main/packages) and it is now seamlessly integrated into Jest. If you are upgrading from an older version of Jest or are looking to adopt Jest, we recommend reading the [Getting Started guide](/docs/getting-started). +`babel-jest` was adopted within the newly modularized Jest [repository](https://github.com/jestjs/jest/tree/main/packages) and it is now seamlessly integrated into Jest. If you are upgrading from an older version of Jest or are looking to adopt Jest, we recommend reading the [Getting Started guide](/docs/getting-started). @@ -78,7 +78,7 @@ We recently wrote about some [performance improvements](/blog/2016/03/11/javascr #### Jasmine and Test Assertion Improvements -When Jest was open sourced it shipped with Jasmine 1. Jest was designed to work with any test assertion library and optional Jasmine 2 support was added through an [external contribution](https://github.com/facebook/jest/pull/330) at the end of last year. This change delivers better performance and provides a better APIs over the previous version of Jasmine. As such, we have converted all our JavaScript tests at Facebook to Jasmine 2. With Jest 11 we are making Jasmine 2 the new default. Jasmine 1 can be enabled through the [`testRunner`](/docs/api#testrunner-string) configuration option. +When Jest was open sourced it shipped with Jasmine 1. Jest was designed to work with any test assertion library and optional Jasmine 2 support was added through an [external contribution](https://github.com/jestjs/jest/pull/330) at the end of last year. This change delivers better performance and provides a better APIs over the previous version of Jasmine. As such, we have converted all our JavaScript tests at Facebook to Jasmine 2. With Jest 11 we are making Jasmine 2 the new default. Jasmine 1 can be enabled through the [`testRunner`](/docs/api#testrunner-string) configuration option. We have also made many updates around Jasmine. The failure messages for custom matchers provided for Jest's mock functions were improved and will now also work for Jasmine spies. Skipped tests, when using `fit` or `fdescribe,` are now properly reported at the end of a test run. @@ -86,7 +86,7 @@ We have also made many updates around Jasmine. The failure messages for custom m The `jest --watch` command has been rewritten and improved. By default it now only runs tests related to changed files. If you want to run all tests on every change, you can run `jest --watch=all`. The verbose logger output has also been improved and we've added more helpful warnings and error messages. We added a [`testEnvironment`](/docs/api#testenvironment-string) configuration option to customize the test environment. For example, when building a node service, a special `node` environment instead of `jsdom` can be used. Finally, the website and all documentation have been completely rewritten. -All changes from the past few months can be found in the [CHANGELOG](https://github.com/facebook/jest/blob/main/CHANGELOG.md). +All changes from the past few months can be found in the [CHANGELOG](https://github.com/jestjs/jest/blob/main/CHANGELOG.md). ### Contributions And Jest's future diff --git a/website/blog/2016-06-22-jest-13.md b/website/blog/2016-06-22-jest-13.md index 2cf9af2ccdf5..7d2310a7fae6 100644 --- a/website/blog/2016-06-22-jest-13.md +++ b/website/blog/2016-06-22-jest-13.md @@ -11,7 +11,7 @@ The Flow project has evolved a lot within Facebook and has been successfully ado -With the help of [lerna](https://github.com/lerna/lerna), we continued to modularize the Jest project. With just a small [update to the configuration](https://github.com/lerna/lerna#lernajson), Flow and lerna now get along well with each other. Splitting up Jest into packages helped us rethink module boundaries and enabled us to ship useful [packages](https://github.com/facebook/jest/tree/main/packages) standalone: The `jest-runtime` and `jest-repl` cli tools now allow you to run scripts in a sandboxed Jest environment, enabling you to run and debug your app from the command line. This is especially helpful for projects that use Facebook's `@providesModule` module convention. To get started, just install `jest-repl` and run it in the same folder you normally run your tests in! We also published a `jest-changed-files` package that finds changed files in version control for either git or hg, a common thing in developer tools. +With the help of [lerna](https://github.com/lerna/lerna), we continued to modularize the Jest project. With just a small [update to the configuration](https://github.com/lerna/lerna#lernajson), Flow and lerna now get along well with each other. Splitting up Jest into packages helped us rethink module boundaries and enabled us to ship useful [packages](https://github.com/jestjs/jest/tree/main/packages) standalone: The `jest-runtime` and `jest-repl` cli tools now allow you to run scripts in a sandboxed Jest environment, enabling you to run and debug your app from the command line. This is especially helpful for projects that use Facebook's `@providesModule` module convention. To get started, just install `jest-repl` and run it in the same folder you normally run your tests in! We also published a `jest-changed-files` package that finds changed files in version control for either git or hg, a common thing in developer tools. ## New and improved features diff --git a/website/blog/2016-07-27-jest-14.md b/website/blog/2016-07-27-jest-14.md index 77ddd42b622b..b9c66f4fa3ce 100644 --- a/website/blog/2016-07-27-jest-14.md +++ b/website/blog/2016-07-27-jest-14.md @@ -11,7 +11,7 @@ One of the big open questions was how to write React tests efficiently. There ar -Together with the React team we created a new test renderer for React and added snapshot testing to Jest. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a simple [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +Together with the React team we created a new test renderer for React and added snapshot testing to Jest. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a simple [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```javascript import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ test('Link renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`Link renders correctly 1`] = ` @@ -43,7 +43,7 @@ If we change the address the Link component in our example is pointing to, Jest ![snapshot-testing](/img/blog/snapshot.png) -Now you know that you either need to accept the changes with `jest -u`, or fix the component if the changes were unintentional. To try out this functionality, please clone the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modify the Link component and run Jest. We updated the [React Tutorial](/docs/tutorial-react) with a new guide for snapshot testing. +Now you know that you either need to accept the changes with `jest -u`, or fix the component if the changes were unintentional. To try out this functionality, please clone the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modify the Link component and run Jest. We updated the [React Tutorial](/docs/tutorial-react) with a new guide for snapshot testing. This feature was built by [Ben Alpert](https://twitter.com/soprano) and [Cristian Carlesso](https://twitter.com/kentaromiura). @@ -60,12 +60,12 @@ You can start using Jest with react-native by running `yarn add --dev jest-react ``` - [Tutorial and setup guide](/docs/tutorial-react-native#content) -- [Example project](https://github.com/facebook/jest/tree/main/examples/react-native) +- [Example project](https://github.com/jestjs/jest/tree/main/examples/react-native) - [Example pull request for _snowflake_](https://github.com/bartonhammond/snowflake/pull/110), a popular react-native open source library. :::info -The preset currently only implements the minimal set of configuration necessary to get started with React Native testing. We are hoping for community contributions to improve this project. Please try it and file [issues](https://github.com/facebook/jest/issues) or send pull requests! +The preset currently only implements the minimal set of configuration necessary to get started with React Native testing. We are hoping for community contributions to improve this project. Please try it and file [issues](https://github.com/jestjs/jest/issues) or send pull requests! ::: @@ -79,7 +79,7 @@ While this was the solution we wanted for the web, we also found many problems w - **Fast iteration speed:** Engineers want to get results in less than a second rather than waiting for minutes or even hours. If tests don't run quickly like in most end-to-end frameworks, engineers don't run them at all or don't bother writing them in the first place. - **Debugging:** It's easy to step into the code of an integration test in JS instead of trying to recreate the screenshot test scenario and debugging what happened in the visual diff. -Because we believe snapshot testing can be useful beyond Jest we split the feature into a [jest-snapshot](https://github.com/facebook/jest/tree/main/packages/jest-snapshot) package. We are happy to work with the community to make it more generic so it can be integrated with other test runners and share concepts and infrastructure with each other. +Because we believe snapshot testing can be useful beyond Jest we split the feature into a [jest-snapshot](https://github.com/jestjs/jest/tree/main/packages/jest-snapshot) package. We are happy to work with the community to make it more generic so it can be integrated with other test runners and share concepts and infrastructure with each other. Finally, here is a quote of a Facebook engineer describing how snapshot testing changed his unit testing experience: diff --git a/website/blog/2016-09-01-jest-15.md b/website/blog/2016-09-01-jest-15.md index e7afc6369dd7..8a874cb1f893 100644 --- a/website/blog/2016-09-01-jest-15.md +++ b/website/blog/2016-09-01-jest-15.md @@ -7,7 +7,7 @@ authorFBID: 100000023028168 We spent the past year making Jest [faster](/blog/2016/03/11/javascript-unit-testing-performance), [easier to configure](/blog/2016/04/12/jest-11), [added tons of features](/blog/2016/06/22/jest-13) and built [snapshot testing](/blog/2016/07/27/jest-14). However, there were two areas where we invested very little: the CLI output and user experience. With Jest 15 we are changing the framework radically to make it easier to use both for beginners and experienced users. We are excited that our investment in Jest is now paying off: we can move fast and improve the framework for Facebook and the open source community at light-speed. Jest's goal is to come with batteries included and to require as little configuration as necessary. We recently got a chance to explain our philosophy on a [create-react-app issue](https://github.com/facebookincubator/create-react-app/pull/250#issuecomment-237098619). -The most important change to talk about is a set of [new defaults](https://github.com/facebook/jest/pull/1511). If you are an existing Jest user you will very likely need to update your configuration for Jest 15. In most cases it will simplify your setup and Jest will provide useful error messages during the upgrade. All of the new defaults can be disabled to suit your needs, but we still consider the disabled features critical for Jest in certain situations and will continue to use and support them at Facebook long-term. Our [API documentation](/docs/api) was also completely rewritten to reflect these changes. [This pull request for React](https://github.com/facebook/react/pull/7625/files) highlights some of the changes necessary for existing projects. +The most important change to talk about is a set of [new defaults](https://github.com/jestjs/jest/pull/1511). If you are an existing Jest user you will very likely need to update your configuration for Jest 15. In most cases it will simplify your setup and Jest will provide useful error messages during the upgrade. All of the new defaults can be disabled to suit your needs, but we still consider the disabled features critical for Jest in certain situations and will continue to use and support them at Facebook long-term. Our [API documentation](/docs/api) was also completely rewritten to reflect these changes. [This pull request for React](https://github.com/facebook/react/pull/7625/files) highlights some of the changes necessary for existing projects. @@ -68,7 +68,7 @@ const React2 = require('react'); React1 !== React2; // These two are separate copies of React. ``` -The call to `resetModules` wipes away the require cache. A second call to require the same module will result in a new instantiation of the same module and all of its dependencies. This feature is especially useful when dealing with modules that have side effects, like [jest-haste-map](https://github.com/facebook/jest/blob/3bbf32a239fc4aad8cc6928a787f235bd86fecac/packages/jest-haste-map/src/__tests__/index-test.js#L64). +The call to `resetModules` wipes away the require cache. A second call to require the same module will result in a new instantiation of the same module and all of its dependencies. This feature is especially useful when dealing with modules that have side effects, like [jest-haste-map](https://github.com/jestjs/jest/blob/3bbf32a239fc4aad8cc6928a787f235bd86fecac/packages/jest-haste-map/src/__tests__/index-test.js#L64). We believe it is better to put users in control so we disabled the implicit reset. Modules can be reset using `jest.resetModules()` in code and the `resetModules` option can be enabled in the configuration to bring back the previous behavior. @@ -86,7 +86,7 @@ The `setupEnvScriptFile` configuration option has been deprecated for a while. J ## Rewritten Code Coverage Support -Code coverage in Jest can be used through `jest --coverage` and requires no additional packages or configuration. Code coverage support was completely rewritten and a new `collectCoverageFrom` option was added to collect code coverage information from entire projects, including **untested files**. Note that this option uses globs as we are hoping to further simplify configuration options in the future and provide a simpler alternative to regular expressions. See Jest's [package.json](https://github.com/facebook/jest/blob/9088f6517813f6c089cf52e980d6579511dcde88/package.json#L47) for an example. +Code coverage in Jest can be used through `jest --coverage` and requires no additional packages or configuration. Code coverage support was completely rewritten and a new `collectCoverageFrom` option was added to collect code coverage information from entire projects, including **untested files**. Note that this option uses globs as we are hoping to further simplify configuration options in the future and provide a simpler alternative to regular expressions. See Jest's [package.json](https://github.com/jestjs/jest/blob/9088f6517813f6c089cf52e980d6579511dcde88/package.json#L47) for an example. ## Other Improvements @@ -102,6 +102,6 @@ A huge number of other improvements were also made: - Fix `testEnvironment` resolution to prefer `jest-environment-{name}` instead of `{name}` only. This prevents a module collision when using `jsdom` as test environment. - Improvements to Jest's own test infra by merging integration and unit tests. Code coverage is now collected for Jest. -We are happy when looking back at all the changes we have made together with the help from the community and couldn't be more excited to make Jest even better over the course of the next few months. Please [file an issue](https://github.com/facebook/jest/issues) if something isn't working as expected and send us pull requests. +We are happy when looking back at all the changes we have made together with the help from the community and couldn't be more excited to make Jest even better over the course of the next few months. Please [file an issue](https://github.com/jestjs/jest/issues) if something isn't working as expected and send us pull requests. -Next up: [Concurrent Reporter](https://github.com/facebook/jest/pull/1480). +Next up: [Concurrent Reporter](https://github.com/jestjs/jest/pull/1480). diff --git a/website/blog/2016-10-03-jest-16.md b/website/blog/2016-10-03-jest-16.md index 3e718ab2a7d4..1e5f5600d18d 100644 --- a/website/blog/2016-10-03-jest-16.md +++ b/website/blog/2016-10-03-jest-16.md @@ -76,4 +76,4 @@ Other highlights about snapshot testing: If you are using other test runners, Kenneth Skovhus built an awesome [jest-codemods](https://github.com/skovhus/jest-codemods) library that will automate the conversion for you. Codemods are awesome: they'll allow you to quickly evaluate whether Jest will work for you. Give it a try! -The full [changelog can be found on GitHub](https://github.com/facebook/jest/blob/main/CHANGELOG.md#jest-1600). Jest 16 was a true JavaScript community effort and the project now has more than 220 contributors. We thank each and every one of you for your help to make this project great. +The full [changelog can be found on GitHub](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#jest-1600). Jest 16 was a true JavaScript community effort and the project now has more than 220 contributors. We thank each and every one of you for your help to make this project great. diff --git a/website/blog/2016-12-15-2016-in-jest.md b/website/blog/2016-12-15-2016-in-jest.md index 307c7319930a..70cfd0940589 100644 --- a/website/blog/2016-12-15-2016-in-jest.md +++ b/website/blog/2016-12-15-2016-in-jest.md @@ -5,15 +5,15 @@ authorURL: http://twitter.com/cpojer authorFBID: 100000023028168 --- -2016 was a big year for JavaScript testing with Jest. In the first six months of the year we rewrote Jest and built a solid foundation to significantly improve performance and the developer experience of testing JavaScript code. We flow-typed the entire codebase, built a ton of integration tests for Jest itself and adopted [lerna](https://lernajs.io/) to turn Jest from a framework into a [_Painless JavaScript Testing platform_](https://github.com/facebook/jest/tree/main/packages). +2016 was a big year for JavaScript testing with Jest. In the first six months of the year we rewrote Jest and built a solid foundation to significantly improve performance and the developer experience of testing JavaScript code. We flow-typed the entire codebase, built a ton of integration tests for Jest itself and adopted [lerna](https://lernajs.io/) to turn Jest from a framework into a [_Painless JavaScript Testing platform_](https://github.com/jestjs/jest/tree/main/packages). The newly created [react-test-renderer](https://yarnpkg.com/en/package/react-test-renderer) finally enabled testing of react-native components. Through the jest-react-native preset (now merged directly into react-native) Jest now works out of the box for any React project and comes pre-configured in [create-react-app](https://github.com/facebookincubator/create-react-app) and [react-native](https://github.com/facebook/react-native) projects. We integrated core pieces of Jest into [react-native's packager](https://github.com/facebook/react-native/tree/main/packager/react-packager/src) and the completely new snapshot testing feature has since been used outside of Jest: It was integrated with React Storybook as “[storyshots](https://github.com/storybooks/storyshots)” and is being adopted by other test runners like [ava](https://github.com/avajs/ava/pull/1113). -The [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) project was rewritten with performance in mind to drive Jest's snapshot feature, was recently merged into Jest's monorepo and is also helpful in other [test runners](https://github.com/avajs/ava/pull/1154). Nowadays Jest is much more about collecting different ideas and solutions to testing than it is about one specific implementation of a test framework. +The [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) project was rewritten with performance in mind to drive Jest's snapshot feature, was recently merged into Jest's monorepo and is also helpful in other [test runners](https://github.com/avajs/ava/pull/1154). Nowadays Jest is much more about collecting different ideas and solutions to testing than it is about one specific implementation of a test framework. -I'd like to deeply thank all the people that have [contributed to Jest this year](https://github.com/facebook/jest/graphs/contributors?from=2016-01-01&to=2016-12-14&type=c), both from the open source community and at Facebook: Dmitrii Abramov, Cristian Carlesso, Dan Abramov, Daniel Lo Nigro, Maxim Derbin, Evan Scott, Forbes Lindesay, Keyan Zhang and 60 more people. We'd also like to welcome [Michał Pierzchała (@thymikee)](https://twitter.com/thymikee) as first official external contributor to Jest. He's been doing a great job managing the issues and PRs on the repo. If you'd like to start contributing to Jest, we have a bunch of [good first tasks](https://github.com/facebook/jest/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+bug%22) and we are always happy to help on our [discord channel](https://discord.gg/j6FKKQQrW9). +I'd like to deeply thank all the people that have [contributed to Jest this year](https://github.com/jestjs/jest/graphs/contributors?from=2016-01-01&to=2016-12-14&type=c), both from the open source community and at Facebook: Dmitrii Abramov, Cristian Carlesso, Dan Abramov, Daniel Lo Nigro, Maxim Derbin, Evan Scott, Forbes Lindesay, Keyan Zhang and 60 more people. We'd also like to welcome [Michał Pierzchała (@thymikee)](https://twitter.com/thymikee) as first official external contributor to Jest. He's been doing a great job managing the issues and PRs on the repo. If you'd like to start contributing to Jest, we have a bunch of [good first tasks](https://github.com/jestjs/jest/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+bug%22) and we are always happy to help on our [discord channel](https://discord.gg/j6FKKQQrW9). ## [repl.it](http://repl.it/) with Jest integration @@ -45,7 +45,7 @@ Here is what happened in the community in the last two months: - Emil Ong wrote about why [“TDD'ing your frontend seems pointless”](https://engineering.haus.com/why-tdding-your-frontend-feels-pointless-5f710fea7325#.pql79knnm). - Nate Hunzaker wrote about [end-to-end testing with Jest and Nightmare](https://www.viget.com/articles/acceptance-testing-react-apps-with-jest-and-nightmare). - [Using Jest with Angular just works](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251#.h9badqevy) according to Matthieu Lux. -- A fantastic conversation about the [purpose of snapshot testing](https://github.com/facebook/jest/issues/2197) is happening right now. +- A fantastic conversation about the [purpose of snapshot testing](https://github.com/jestjs/jest/issues/2197) is happening right now. - Dmitrii made a new [music video with his metal band](https://twitter.com/abramov_dmitrii/status/806613542447157248). - [lazyspec](https://yarnpkg.com/en/package/lazyspec) can help you create smoke tests quickly if you are introducing tests to an existing codebase. - Patrick Stapfer did a lightning talk about [vim and Jest](https://twitter.com/ryyppy/status/803871975995277312). @@ -53,7 +53,7 @@ Here is what happened in the community in the last two months: ## New features, changes and fixes in Jest 17 & 18 -Jest was initially created more than five years ago and as such an old framework it has accumulated some technical debt. This is why we tend to make breaking changes more often than may seem necessary: We believe it is important to incrementally reduce technical debt to ensure that Jest as a project stays maintainable long-term. We didn't announce Jest 17 in a blog post and if you haven't upgraded to it in the last month you may find the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md) useful. +Jest was initially created more than five years ago and as such an old framework it has accumulated some technical debt. This is why we tend to make breaking changes more often than may seem necessary: We believe it is important to incrementally reduce technical debt to ensure that Jest as a project stays maintainable long-term. We didn't announce Jest 17 in a blog post and if you haven't upgraded to it in the last month you may find the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md) useful. - **Breaking:** Removed `pit` in favor of `it` or `test` and `mockImpl` in favor of `jest.fn()` or `mockImplementation` . - **Breaking:** Renamed `--jsonOutputFile` to `--outputFile`. @@ -99,7 +99,7 @@ Jest was initially created more than five years ago and as such an old framework Six months ago [we shared our plans for Jest](/blog/2016/07/27/jest-14#what-s-next-for-jest) and we are happy that we were able to execute well on almost all of them. For the next six months, here is what we are planning: -- **Instant feedback:** [Nuclide](https://nuclide.io/) integration and an improved and [faster watch mode](https://github.com/facebook/jest/pull/2324#issuecomment-267149669). +- **Instant feedback:** [Nuclide](https://nuclide.io/) integration and an improved and [faster watch mode](https://github.com/jestjs/jest/pull/2324#issuecomment-267149669). - **Improved developer experience:** new mocking APIs and improved assertions. - **Better performance and memory usage:** analyze Jest and be more conscious about efficiency. - **Snapshot Improvements:** snapshot approval mode, syntax highlighting and improved `react-test-renderer` APIs. diff --git a/website/blog/2017-01-30-a-great-developer-experience.md b/website/blog/2017-01-30-a-great-developer-experience.md index 91a6c65a99e1..a59fb088108c 100644 --- a/website/blog/2017-01-30-a-great-developer-experience.md +++ b/website/blog/2017-01-30-a-great-developer-experience.md @@ -47,6 +47,6 @@ As highlighted [last month](/blog/2016/12/15/2016-in-jest), it is now possible t ## Get involved -This is just the start. Go ahead and take a look at the docs, and don't hesitate to send any feedback our way. If you find a mistake in the docs or you just want to let us know what needs to be documented better, please tweet at us at [@jestjs\_](https://twitter.com/jestjs_), [open an issue on GitHub](https://github.com/facebook/jest/issues), or send us a PR by clicking "Edit on GitHub" at the top of the doc. +This is just the start. Go ahead and take a look at the docs, and don't hesitate to send any feedback our way. If you find a mistake in the docs or you just want to let us know what needs to be documented better, please tweet at us at [@jestjs\_](https://twitter.com/jestjs_), [open an issue on GitHub](https://github.com/jestjs/jest/issues), or send us a PR by clicking "Edit on GitHub" at the top of the doc. We're really excited for the year ahead and can't wait to hear from you! diff --git a/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md b/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md index 17b282aff06d..3d2094b47521 100644 --- a/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md +++ b/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md @@ -9,7 +9,7 @@ Today we are pleased to ship version 19 of the Jest testing platform. It's the b ## Immersive Watch Mode -We [completely rewrote the watch mode](https://github.com/facebook/jest/pull/2362) to make it instant and more extensible. As a result, the experience of using it really is immersive: tests re-run instantly after a file change and we made it easy to select the right tests. +We [completely rewrote the watch mode](https://github.com/jestjs/jest/pull/2362) to make it instant and more extensible. As a result, the experience of using it really is immersive: tests re-run instantly after a file change and we made it easy to select the right tests. @@ -81,19 +81,19 @@ We now also error on invalid CLI arguments instead of ignoring them. But we've g - [`expect.stringContaining`](/docs/expect#expectstringcontainingstring) - [`jest.spyOn`](/docs/jest-object#jestspyonobject-methodname) -We're close to almost full feature parity with the `expect` npm package. [Michael Jackson](https://twitter.com/mjackson), the author of the package, agreed to [donate](https://github.com/facebook/jest/issues/1679) it to the Jest project, which means that `jest-matchers` will be renamed to `expect`. Since our version of `expect` is not intended to be fully compatible, [Christopher Chedeau](https://twitter.com/Vjeux) is working on a codemod to make the transition painless. Christopher also worked on a number of improvements to `jest-matchers` which enables it to be used outside of Jest and even [works inside browsers](https://github.com/facebook/jest/pull/2795). +We're close to almost full feature parity with the `expect` npm package. [Michael Jackson](https://twitter.com/mjackson), the author of the package, agreed to [donate](https://github.com/jestjs/jest/issues/1679) it to the Jest project, which means that `jest-matchers` will be renamed to `expect`. Since our version of `expect` is not intended to be fully compatible, [Christopher Chedeau](https://twitter.com/Vjeux) is working on a codemod to make the transition painless. Christopher also worked on a number of improvements to `jest-matchers` which enables it to be used outside of Jest and even [works inside browsers](https://github.com/jestjs/jest/pull/2795). -## [eslint-plugin-jest](https://github.com/facebook/jest/tree/main/packages/eslint-plugin-jest) – our very own ESLint plugin +## [eslint-plugin-jest](https://github.com/jestjs/jest/tree/main/packages/eslint-plugin-jest) – our very own ESLint plugin Thanks to [Jonathan Kim](https://twitter.com/jonnykim) Jest finally has its own official ESLint plugin. It exposes three rules: -- [no-disabled-tests](https://github.com/facebook/jest/blob/main/packages/eslint-plugin-jest/docs/rules/no-disabled-tests.md) - this rule prevents you from accidentally committing disabled tests. -- [no-focused-tests](https://github.com/facebook/jest/blob/main/packages/eslint-plugin-jest/docs/rules/no-focused-tests.md) - this rule prevents you from committing focused tests which would disable all other tests in the same suite. -- [no-identical-title](https://github.com/facebook/jest/blob/main/packages/eslint-plugin-jest/docs/rules/no-identical-title.md) - disallows identical titles in test names. +- [no-disabled-tests](https://github.com/jestjs/jest/blob/main/packages/eslint-plugin-jest/docs/rules/no-disabled-tests.md) - this rule prevents you from accidentally committing disabled tests. +- [no-focused-tests](https://github.com/jestjs/jest/blob/main/packages/eslint-plugin-jest/docs/rules/no-focused-tests.md) - this rule prevents you from committing focused tests which would disable all other tests in the same suite. +- [no-identical-title](https://github.com/jestjs/jest/blob/main/packages/eslint-plugin-jest/docs/rules/no-identical-title.md) - disallows identical titles in test names. You can install it using `npm install --save-dev eslint-plugin-jest` or `yarn add --dev eslint eslint-plugin-jest` and it can be enabled by adding `{"plugins": ["jest"]}` to your eslint configuration. -## New public package: [jest-validate](https://github.com/facebook/jest/tree/main/packages/jest-validate) +## New public package: [jest-validate](https://github.com/jestjs/jest/tree/main/packages/jest-validate) While we refactored the validation and normalization code for Jest's configuration, we were so happy with the new error messaging that we extracted it to its own module to share it with everyone. With Jest 19 we welcome `jest-validate` to our self-sustained packages family. @@ -135,12 +135,12 @@ The homepage was completely redesigned to be more descriptive of what Jest is ab - Stephen Scott wrote a detailed article about [testing React components](https://medium.freecodecamp.com/the-right-way-to-test-react-components-548a4736ab22) in which he weighs the pros and cons of different approaches. - [Using Jest with vue.js](https://medium.com/@kentaromiura_the_js_guy/jest-for-all-episode-1-vue-js-d616bccbe186#.r8ryxlw98) got a lot easier after reading Cristian Carlesso's blog post. - [Michele Bertoli wrote a book about React Design Patterns and Best Practices](https://twitter.com/cpojer/status/825004258219130880) which features an entire section about Jest. -- Improved `--notify` command that shows an operating system notification which [can now also re-run tests from the notification](https://github.com/facebook/jest/pull/2727). This is actually a Jest feature and we are just checking if you are still reading this blog post. +- Improved `--notify` command that shows an operating system notification which [can now also re-run tests from the notification](https://github.com/jestjs/jest/pull/2727). This is actually a Jest feature and we are just checking if you are still reading this blog post. - Jest is now part of [react-boilerplate](https://twitter.com/mxstbr/status/820326656439177217). - Read about the [hidden powers of Jest's matchers](https://medium.com/@boriscoder/the-hidden-power-of-jest-matchers-f3d86d8101b0#.pn10z1pzx). -Finally, we are happy to announce that the [ava](https://github.com/avajs/ava) test runner has adopted parts of the Jest platform and is now shipping with basic [snapshot support](https://github.com/avajs/ava#snapshot-testing) and is using [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format). Consolidating test infrastructure makes it easier to learn how to test applications and enables us to share best practices. We are looking forward to see what we can learn from existing test libraries in the future. +Finally, we are happy to announce that the [ava](https://github.com/avajs/ava) test runner has adopted parts of the Jest platform and is now shipping with basic [snapshot support](https://github.com/avajs/ava#snapshot-testing) and is using [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format). Consolidating test infrastructure makes it easier to learn how to test applications and enables us to share best practices. We are looking forward to see what we can learn from existing test libraries in the future. -The full [changelog can be found on GitHub](https://github.com/facebook/jest/blob/main/CHANGELOG.md#jest-1900). Jest 19 was a true JavaScript community effort with [17 people who contributed](https://github.com/facebook/jest/graphs/contributors?from=2016-12-23&to=2017-02-21&type=c) to this release. We thank each and every one of you for your help to make this project great. +The full [changelog can be found on GitHub](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#jest-1900). Jest 19 was a true JavaScript community effort with [17 people who contributed](https://github.com/jestjs/jest/graphs/contributors?from=2016-12-23&to=2017-02-21&type=c) to this release. We thank each and every one of you for your help to make this project great. _This blog post was written by [Rogelio Guzman](https://twitter.com/rogeliog) and [Michał Pierzchała](https://twitter.com/thymikee)._ diff --git a/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md b/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md index aa7ed8bbe447..0764f16dbf0a 100644 --- a/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md +++ b/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md @@ -78,7 +78,7 @@ As with every major release, we are making a number of breaking changes to make - **Translations:** We are now asking for your help to [translate the Jest documentation](https://crowdin.com/project/jest-v2) to make it easier for people to learn how to use Jest. - **Custom Reporters:** Jest now supports custom test reporters through the `reporters` configuration option. You can finally customize the output of Jest as well as integrate it with other tools by generating reports in formats such as XML. [See documentation](/docs/configuration#reporters-array-modulename-modulename-options). - **Codebase Health:** It was only possible iterate so quickly in Jest because we spent a significant amount of time on the health of the codebase. We were one of the early adopters of [prettier](https://github.com/prettier/prettier), we notably increased flow coverage, forked Jasmine to improve our test runner library and we rewrote and refactored significant portions of Jest itself to set up Jest for success in the future. -- **Bugfixes:** As always, we made plenty of bugfixes in Jest. The full changelog can be found in the [Jest repository](https://github.com/facebook/jest/blob/main/CHANGELOG.md#jest-2000). +- **Bugfixes:** As always, we made plenty of bugfixes in Jest. The full changelog can be found in the [Jest repository](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#jest-2000). ## Talks about Jest @@ -87,4 +87,4 @@ Recently the Jest core team and other contributors started to talk more about Je - Rogelio Guzman did a talk about [Jest Snapshots and Beyond](https://www.youtube.com/watch?time_continue=416&v=HAuXJVI_bUs) at React Conf. - I spoke about [Building High-Quality JavaScript Tools](https://developers.facebook.com/videos/f8-2017/building-high-quality-javascript-tools/) at Facebook's F8 conference. -_As always, this release couldn't have been possible without you, the JavaScript community. We are incredibly grateful that we get the opportunity to work on improving JavaScript testing together. If you'd like to contribute to Jest, please don't hesitate to reach out to us on [GitHub](https://github.com/facebook/jest) or on [Discord](https://discord.gg/j6FKKQQrW9)._ +_As always, this release couldn't have been possible without you, the JavaScript community. We are incredibly grateful that we get the opportunity to work on improving JavaScript testing together. If you'd like to contribute to Jest, please don't hesitate to reach out to us on [GitHub](https://github.com/jestjs/jest) or on [Discord](https://discord.gg/j6FKKQQrW9)._ diff --git a/website/blog/2017-12-18-jest-22.md b/website/blog/2017-12-18-jest-22.md index 7d5ebb915953..f1fd8367f77f 100644 --- a/website/blog/2017-12-18-jest-22.md +++ b/website/blog/2017-12-18-jest-22.md @@ -5,7 +5,7 @@ authorURL: https://github.com/SimenB authorFBID: 100003004880942 --- -Today we are announcing a new major version of Jest which refines almost all parts of Jest to provide a more solid testing foundation. Together with the Jest community we made a number of changes across the board that will help you get more out of Jest. We are also graduating the custom runners feature out of the experimental stage and added a new package, `jest-worker`, for parallelizing work across multiple processes. We have compiled a list of highlights below but make sure to check out the (as always) [massive changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md). +Today we are announcing a new major version of Jest which refines almost all parts of Jest to provide a more solid testing foundation. Together with the Jest community we made a number of changes across the board that will help you get more out of Jest. We are also graduating the custom runners feature out of the experimental stage and added a new package, `jest-worker`, for parallelizing work across multiple processes. We have compiled a list of highlights below but make sure to check out the (as always) [massive changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md). @@ -67,11 +67,11 @@ When [Puppeteer](https://github.com/GoogleChrome/puppeteer/), a way of programma ## Experimental Leak Detection -We added an experimental `--detectLeaks` setting to Jest that will let you know if your internal environment instance is leaked after a test execution. It will also warn you when your test suite tries to require a file after the test has finished, meaning you forgot to wait for all async operations or left something not properly cleaned. This will however not discover leaks in user land code, only in test land code; although the technology used behind it can help you (see `jest-leak-detector`). If you are reporting a bug about Jest's memory usage, please provide a repro where `--detectLeaks` will make the test suite fail. We [started building a better sandboxing mechanism](https://github.com/facebook/jest/pull/4970) for Jest but it's not ready yet to be enabled by default. If you'd like to help, please reach out to us on discord! +We added an experimental `--detectLeaks` setting to Jest that will let you know if your internal environment instance is leaked after a test execution. It will also warn you when your test suite tries to require a file after the test has finished, meaning you forgot to wait for all async operations or left something not properly cleaned. This will however not discover leaks in user land code, only in test land code; although the technology used behind it can help you (see `jest-leak-detector`). If you are reporting a bug about Jest's memory usage, please provide a repro where `--detectLeaks` will make the test suite fail. We [started building a better sandboxing mechanism](https://github.com/jestjs/jest/pull/4970) for Jest but it's not ready yet to be enabled by default. If you'd like to help, please reach out to us on discord! ## Watch Mode Refinements -When using watch mode, there is now a way to [focus only on tests that previously failed](https://github.com/facebook/jest/pull/4886). In this mode, Jest will not re-run previously passing tests which should help you iron out all test failures. Additionally, [we added a plugin system to watch mode](https://github.com/facebook/jest/pull/4841). By adding modules to `watchPlugins` in your configuration you can extend the features of the watch mode. +When using watch mode, there is now a way to [focus only on tests that previously failed](https://github.com/jestjs/jest/pull/4886). In this mode, Jest will not re-run previously passing tests which should help you iron out all test failures. Additionally, [we added a plugin system to watch mode](https://github.com/jestjs/jest/pull/4841). By adding modules to `watchPlugins` in your configuration you can extend the features of the watch mode. ## Babel 7 support @@ -110,7 +110,7 @@ exports[`my mocking test 1`] = ` Jest 21 was released back in September, and we unfortunately never got around to write a blog post. So here is a quick summary of the main changes in version 21: -1. **Use expect and jest-mock in the browser:** [Michael Jackson](https://github.com/mjackson) donated his excellent [`expect`](https://github.com/mjackson/expect) package to the Jest project. As part of that transition, the Jest core team, with much help from [Kenneth Skovhus](https://github.com/skovhus/), made both `jest-matchers` (renamed to `expect`) and `jest-mock` work in browsers. This means that while you cannot use Jest itself in browsers ([yet](https://github.com/facebook/jest/issues/848)), you can use its awesome assertions and mocks for instance as replacements for Chai and Sinon running in Mocha tests. If you are migrating from earlier `expect` to the new Jest-powered `expect`, you can use [`jest-codemods`](https://github.com/skovhus/jest-codemods/) to automate the migration. +1. **Use expect and jest-mock in the browser:** [Michael Jackson](https://github.com/mjackson) donated his excellent [`expect`](https://github.com/mjackson/expect) package to the Jest project. As part of that transition, the Jest core team, with much help from [Kenneth Skovhus](https://github.com/skovhus/), made both `jest-matchers` (renamed to `expect`) and `jest-mock` work in browsers. This means that while you cannot use Jest itself in browsers ([yet](https://github.com/jestjs/jest/issues/848)), you can use its awesome assertions and mocks for instance as replacements for Chai and Sinon running in Mocha tests. If you are migrating from earlier `expect` to the new Jest-powered `expect`, you can use [`jest-codemods`](https://github.com/skovhus/jest-codemods/) to automate the migration. 2. **MIT License:** We changed Jest's license to MIT. _Yay!_ 3. **Fail test suites on async errors:** Jest used to have a bug that made it crash when errors were thrown in certain parts of async code. This was fixed by community contributors. 4. **Faster startup:** With Jest 21 we fine tuned Jest's startup to be more than 50% faster. The large overhead of Jest when running it on a small and fast test was always an issue for us and now this shouldn't be a reason to hold you back from using Jest any longer. diff --git a/website/blog/2018-05-29-jest-23-blazing-fast-delightful-testing.md b/website/blog/2018-05-29-jest-23-blazing-fast-delightful-testing.md index 88b758e754ff..132594a4e49d 100644 --- a/website/blog/2018-05-29-jest-23-blazing-fast-delightful-testing.md +++ b/website/blog/2018-05-29-jest-23-blazing-fast-delightful-testing.md @@ -13,7 +13,7 @@ Here's are some of the Jest 23 highlights and breaking changes. -For a full list see the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md). +For a full list see the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md). ## Interactive Snapshot Mode @@ -130,4 +130,4 @@ Full talk is available [here](https://www.youtube.com/watch?v=cAKYQpTC7MA). The turnout was amazing, and we were able to meet a lot of the London-based community in person. Thank you to everyone who joined us and for your continued support! Stay tuned for our next post which will outline the Jest Open Collective and the plans we have for the future. -_As always, this release couldn't have been possible without you, the JavaScript community. We are incredibly grateful that we get the opportunity to work on improving JavaScript testing together. If you'd like to contribute to Jest, please don't hesitate to reach out to us on_ _[GitHub](https://github.com/facebook/jest) or on_ _[Discord](https://discord.gg/j6FKKQQrW9)._ +_As always, this release couldn't have been possible without you, the JavaScript community. We are incredibly grateful that we get the opportunity to work on improving JavaScript testing together. If you'd like to contribute to Jest, please don't hesitate to reach out to us on_ _[GitHub](https://github.com/jestjs/jest) or on_ _[Discord](https://discord.gg/j6FKKQQrW9)._ diff --git a/website/blog/2019-01-25-jest-24-refreshing-polished-typescript-friendly.md b/website/blog/2019-01-25-jest-24-refreshing-polished-typescript-friendly.md index 2083a34edebe..580fec8b6668 100644 --- a/website/blog/2019-01-25-jest-24-refreshing-polished-typescript-friendly.md +++ b/website/blog/2019-01-25-jest-24-refreshing-polished-typescript-friendly.md @@ -7,7 +7,7 @@ authorFBID: 100003004880942 Today we are happy to announce the next major release of Jest - version 24! It's been 4 months since the last minor release, and 8 months since Jest 23, so this upgrade is a big one, with something for everyone! Highlights include built-in support for TypeScript by upgrading the Jest internals to Babel 7, fixing some long-standing issues with missing console output and performance issues when computing large diffs, and a brand new sparkling website. ✨ -For a full list of all changes see the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md). +For a full list of all changes see the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md). @@ -15,7 +15,7 @@ For a full list of all changes see the [changelog](https://github.com/facebook/j [@orta](https://twitter.com/orta) has provided a beautiful redesign of Jest's website, which has been implemented by community members [@montogeek](https://twitter.com/montogeek) and [@brainkim](https://github.com/brainkim). -The aim of the redesign was to highlight more of what makes Jest awesome, and to decouple the idea that Jest is primarily a tool for testing React apps - you can use Jest with all sorts of projects and we want to make that obvious. You can read more about the ideas behind the redesign in [this issue](https://github.com/facebook/jest/issues/7265). +The aim of the redesign was to highlight more of what makes Jest awesome, and to decouple the idea that Jest is primarily a tool for testing React apps - you can use Jest with all sorts of projects and we want to make that obvious. You can read more about the ideas behind the redesign in [this issue](https://github.com/jestjs/jest/issues/7265). ## TypeScript support @@ -51,7 +51,7 @@ test.todo('missing options should be normalized'); When tests fail, you need to make confident and correct decisions which changes are expected progress and which changes are unexpected regressions. It is especially important not to miss a few regressions hidden among much progress. Jest 24 makes reports when assertions fail more clear and concise for several matchers. Because the effort will continue in Jest 25, you might notice some temporary inconsistencies. If your tests never fail, then you won't get to see them - for the rest of us, it'll be easier to debug why something isn't working as expected. Thanks for the hard work by [@ittordepam](https://twitter.com/ittordepam) and other contributors from the community. -You can see these changes across all these PRs: [7621](https://github.com/facebook/jest/pull/7621), [7557](https://github.com/facebook/jest/pull/7557), [7448](https://github.com/facebook/jest/pull/7448), [7325](https://github.com/facebook/jest/pull/7325), [7241](https://github.com/facebook/jest/pull/7241), [7152](https://github.com/facebook/jest/pull/7152), [7125](https://github.com/facebook/jest/pull/7125), [7107](https://github.com/facebook/jest/pull/7107), [6961](https://github.com/facebook/jest/pull/6961). +You can see these changes across all these PRs: [7621](https://github.com/jestjs/jest/pull/7621), [7557](https://github.com/jestjs/jest/pull/7557), [7448](https://github.com/jestjs/jest/pull/7448), [7325](https://github.com/jestjs/jest/pull/7325), [7241](https://github.com/jestjs/jest/pull/7241), [7152](https://github.com/jestjs/jest/pull/7152), [7125](https://github.com/jestjs/jest/pull/7125), [7107](https://github.com/jestjs/jest/pull/7107), [6961](https://github.com/jestjs/jest/pull/6961). Examples: @@ -71,27 +71,27 @@ Mock function not called We've fixed a couple of really old issues in this release. -The first one we'd like to highlight is `console.log` statements going missing. Jest intercepts and collects all logs in order to give you a stack trace to them, as well as provide them to reporters so you can handle them however you want. However, this has led to an issue where they have simply been missing in certain edge cases. Luckily for Jest 24, [@spion](https://twitter.com/spion) has [stepped up](https://github.com/facebook/jest/pull/6871) and fixed this issue. Thank you very much! +The first one we'd like to highlight is `console.log` statements going missing. Jest intercepts and collects all logs in order to give you a stack trace to them, as well as provide them to reporters so you can handle them however you want. However, this has led to an issue where they have simply been missing in certain edge cases. Luckily for Jest 24, [@spion](https://twitter.com/spion) has [stepped up](https://github.com/jestjs/jest/pull/6871) and fixed this issue. Thank you very much! -The second one is an issue where Jest runs out of memory if the difference in serialization of expected and received value has a huge number of insertion changes (either unexpected because of mistake in test or defect in serializer or expected because of temporary failures during test-driven development). [@ittordepam](https://twitter.com/ittordepam) has [replaced](https://github.com/facebook/jest/pull/6961) the previous diffing algorithm with `diff-sequences` package, which should fix this issue because it uses the theoretical minimum amount of memory. It opens up possibility for word-diffs in the future, similar to what [git provides](https://git-scm.com/docs/git-diff#git-diff---word-diffltmodegt). Please see [this PR](https://github.com/facebook/jest/pull/4619) and don't hesitate to reach out if you want to help make that happen! +The second one is an issue where Jest runs out of memory if the difference in serialization of expected and received value has a huge number of insertion changes (either unexpected because of mistake in test or defect in serializer or expected because of temporary failures during test-driven development). [@ittordepam](https://twitter.com/ittordepam) has [replaced](https://github.com/jestjs/jest/pull/6961) the previous diffing algorithm with `diff-sequences` package, which should fix this issue because it uses the theoretical minimum amount of memory. It opens up possibility for word-diffs in the future, similar to what [git provides](https://git-scm.com/docs/git-diff#git-diff---word-diffltmodegt). Please see [this PR](https://github.com/jestjs/jest/pull/4619) and don't hesitate to reach out if you want to help make that happen! ## Other highlights - We have some improvements for `globalSetup` and `globalTeardown` as well - code transformation will be applied to them similar to `setupFiles` and they are now supported as part of `projects`. -- You can [configure](https://github.com/facebook/jest/pull/6143) Jest's snapshot location, this is mainly useful if you are building tools which use Jest in a larger build process. +- You can [configure](https://github.com/jestjs/jest/pull/6143) Jest's snapshot location, this is mainly useful if you are building tools which use Jest in a larger build process. - A quirk of Jest's CLI has been that while some flags and options have been camel cased (such as `runInBand`), others have not been (such as `no-cache`). In Jest 24, both are recognized, meaning you can write your CLI arguments however you want. - We've renamed `setupTestFrameworkScriptFile` to `setupFilesAfterEnv`, and made it into an array. We hope this will make it more obvious what the options is for. We have plans to further overhaul the configuration in the next major, see the paragraph in the section below. - To reduce the amount of magic Jest performs to “just work™”, in this release we decided to drop automatic injection of `regenerator-runtime`, which is sometimes used in compiled async code. Including `regenerator-runtime` is not always necessary and we believe it's the user's responsibility to include it if it's needed. If you use `@babel/preset-env` with `targets` set to a modern Node version (e.g. Node 6+) you will not need to include it. Please see our [Using Babel docs](/docs/getting-started#using-babel) for more information. -- Node.js 10 came with an experimental module [called `worker_threads`](https://nodejs.org/api/worker_threads.html), which is similar to Worker threads in the browser. `jest-worker`, part of the [Jest platform](/docs/jest-platform), will be able to use `worker_threads` if available instead of `child_process`, which makes it even faster! [Benchmarks](https://github.com/facebook/jest/pull/6676) show a 50% improvement. Due to its experimental nature, it's not enabled when using Jest as a test runner, but you can use it in your own projects today! We plan to enable it by default when it's promoted from experimental status in Node.js. +- Node.js 10 came with an experimental module [called `worker_threads`](https://nodejs.org/api/worker_threads.html), which is similar to Worker threads in the browser. `jest-worker`, part of the [Jest platform](/docs/jest-platform), will be able to use `worker_threads` if available instead of `child_process`, which makes it even faster! [Benchmarks](https://github.com/jestjs/jest/pull/6676) show a 50% improvement. Due to its experimental nature, it's not enabled when using Jest as a test runner, but you can use it in your own projects today! We plan to enable it by default when it's promoted from experimental status in Node.js. ## Breaking Changes -While all breaking changes are listed in the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md), there's a few of them that are worth highlighting: +While all breaking changes are listed in the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md), there's a few of them that are worth highlighting: - We've upgraded to Micromatch 3. While this might not affect every user, it is stricter in its parsing of globs than version 2, which is used in Jest 23. Please read through [this](https://github.com/micromatch/micromatch/issues/133#issuecomment-404211484) and linked issues for examples of invalid globs in case you have problems. - We've removed code remnants that was needed for Node 4. It was previously technically possible to run Jest 23 on Node 4 - that is no longer possible without polyfilling and transpiling. -- Some changes to serialization of mock functions in snapshots - make sure to double check your updated snapshots after upgrading. Related [PR](https://github.com/facebook/jest/pull/6381). -- Jest no longer automatically injects `regenerator-runtime` - if you get errors concerning it, make sure to configure Babel to properly transpile `async` functions, using e.g. `@babel/preset-env`. Related [PR](https://github.com/facebook/jest/pull/7595). +- Some changes to serialization of mock functions in snapshots - make sure to double check your updated snapshots after upgrading. Related [PR](https://github.com/jestjs/jest/pull/6381). +- Jest no longer automatically injects `regenerator-runtime` - if you get errors concerning it, make sure to configure Babel to properly transpile `async` functions, using e.g. `@babel/preset-env`. Related [PR](https://github.com/jestjs/jest/pull/7595). ## The future @@ -99,11 +99,11 @@ We are incredibly humbled by the results in [State Of JS 2018](https://2018.stat We are very thankful for the trust in us shown by the community, and hope to build on it in the future. We will ensure Jest 24 and future releases will continue to build upon this incredible foundation, and continue to be an integral part of JavaScript developers' toolkits. -This has been the first release where we have explored the idea of using our Open Collective funding to create bug bounties. This worked well in getting non-core developers involved in the implementation of the new landing page, and we're optimistic for a long running bug where Jest globals [are mismatched](https://github.com/facebook/jest/issues/2549) from Node globals. We'd like to do more, if you have a pet bug that's a good candidate for our bounty program, please let us know. In the meantime, you can find all the tickets with a bounty via [the issue label](https://github.com/facebook/jest/labels/Has%20Bounty). +This has been the first release where we have explored the idea of using our Open Collective funding to create bug bounties. This worked well in getting non-core developers involved in the implementation of the new landing page, and we're optimistic for a long running bug where Jest globals [are mismatched](https://github.com/jestjs/jest/issues/2549) from Node globals. We'd like to do more, if you have a pet bug that's a good candidate for our bounty program, please let us know. In the meantime, you can find all the tickets with a bounty via [the issue label](https://github.com/jestjs/jest/labels/Has%20Bounty). -We have already started to make plans for the next release of Jest 25, with the biggest planned feature being an overhaul of our configuration, which is pretty hard to grok, mainly because of overlapping option and mixing globs and regular expressions. Feedback on how you want Jest's configuration to look is very much welcome, and can be submitted in [this issue](https://github.com/facebook/jest/issues/7185). +We have already started to make plans for the next release of Jest 25, with the biggest planned feature being an overhaul of our configuration, which is pretty hard to grok, mainly because of overlapping option and mixing globs and regular expressions. Feedback on how you want Jest's configuration to look is very much welcome, and can be submitted in [this issue](https://github.com/jestjs/jest/issues/7185). -You might also have heard that we are planning to migrate the code base from Flow to TypeScript. We are hopeful that this migration will enable even more contributors to jump in and help make 2019 even better for JavaScript testing. 🚀 The plan is to land this in a minor release in the not too distant future. Feedback on this choice can be added to [the RFC](https://github.com/facebook/jest/pull/7554). +You might also have heard that we are planning to migrate the code base from Flow to TypeScript. We are hopeful that this migration will enable even more contributors to jump in and help make 2019 even better for JavaScript testing. 🚀 The plan is to land this in a minor release in the not too distant future. Feedback on this choice can be added to [the RFC](https://github.com/jestjs/jest/pull/7554). Lastly, if you've ever wondered about how Jest is built, [@cpojer](https://twitter.com/cpojer) has recorded a video with an architectural overview of how Jest is put together under the hood. Feel free to reach out if you have any further questions about it. The video is available on our [website](/docs/architecture). diff --git a/website/blog/2020-01-21-jest-25.md b/website/blog/2020-01-21-jest-25.md index 73a77367f21e..273ccf129106 100644 --- a/website/blog/2020-01-21-jest-25.md +++ b/website/blog/2020-01-21-jest-25.md @@ -7,7 +7,7 @@ authorFBID: 100003004880942 Jest 25 is laying the groundwork for many major changes in the future. As such, we kept breaking changes to a minimum, but internal architecture changes may require attention during the upgrade. The main changes are an upgrade of JSDOM from v11 to v15, 10-15% faster test runs, a new diff view for outdated snapshots and dropped Node 6 support. -There has been more than 200 commits since Jest 24.9 by more than 80 different contributors, so as always, take a look at the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md) for a full list of changes. +There has been more than 200 commits since Jest 24.9 by more than 80 different contributors, so as always, take a look at the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md) for a full list of changes. @@ -70,28 +70,28 @@ Here are some reasons why we chose unique colors: The difference in hue from magenta at 300° to teal/cyan/aqua at 180° gives better color vision accessibility and the light background tint for changed lines gives consistent contrast on light and dark themes. -If you maintain a command line tool, you might find inspiration to improve its accessibility in [#9132](https://github.com/facebook/jest/pull/9132). +If you maintain a command line tool, you might find inspiration to improve its accessibility in [#9132](https://github.com/jestjs/jest/pull/9132). ## ECMAScript Modules support Node 13 has unflagged ESM support, and we have started a tiny bit working towards native support in Jest. Jest 25 includes support for `jest.config.cjs` and `jest.config.mjs` configuration files, but tests themselves cannot yet be written using ESM without something like Babel or TypeScript transforming it into CJS. -The APIs Jest will use are still flagged and experimental, so don't expect support right away. These APIs are something the [Node.js Modules team](https://github.com/nodejs/modules) is actively working on, and we'll be keeping an eye on it moving forward and experiment with them so we can provide feedback. You can subscribe to [this issue](https://github.com/facebook/jest/issues/9430) to get any updates about the implementation status in Jest. +The APIs Jest will use are still flagged and experimental, so don't expect support right away. These APIs are something the [Node.js Modules team](https://github.com/nodejs/modules) is actively working on, and we'll be keeping an eye on it moving forward and experiment with them so we can provide feedback. You can subscribe to [this issue](https://github.com/jestjs/jest/issues/9430) to get any updates about the implementation status in Jest. ## Other improvements and updates -- Jest has passed [1000 unique contributors](https://github.com/facebook/jest/graphs/contributors). This is an incredible milestone! Thank you to everybody who helps us make testing as delightful as possible. +- Jest has passed [1000 unique contributors](https://github.com/jestjs/jest/graphs/contributors). This is an incredible milestone! Thank you to everybody who helps us make testing as delightful as possible. - Thanks to community member [Josh Rosenstein](https://github.com/JoshRosenstein), Jest now comes with support for `BigInt` in most matchers, such as `toBeGreaterThan`. Jest will also understand bigint literals out of the box. - Jest’s feature `--detect-leaks` has been broken for Node 12 and newer - this has been fixed in Jest 25. -- As announced in the blog post for Jest 24, Jest’s code base has been rewritten in TypeScript - this work was completed in Jest 24.3. So if you use any of Jest’s individual parts, you should get great IDE integration. Looking forward, we really want to make Jest mocks play nicer with type systems, and we’d love the community’s help with this. Please chime in [here](https://github.com/facebook/jest/issues/7832) with ideas and send PRs! We’ll also be investigating moving the typings for using Jest as a test runner from DefinitelyTyped into Jest itself. +- As announced in the blog post for Jest 24, Jest’s code base has been rewritten in TypeScript - this work was completed in Jest 24.3. So if you use any of Jest’s individual parts, you should get great IDE integration. Looking forward, we really want to make Jest mocks play nicer with type systems, and we’d love the community’s help with this. Please chime in [here](https://github.com/jestjs/jest/issues/7832) with ideas and send PRs! We’ll also be investigating moving the typings for using Jest as a test runner from DefinitelyTyped into Jest itself. - The `jest-diff` package now exports functions like `diffLinesUnified` and `diffStringsUnified` which have configuration options, so other applications can format differences in a custom way. For more information and code examples, see its new `README.md` file in the Jest repository or on package repositories. - Thanks to community member [Wei An Yen](https://github.com/WeiAnAn), Jest will no longer highlight passing asymmetric matchers in expectation errors. This has been a long-standing pain point with asymmetric matchers and we're very happy it's finally solved. - For the second year running, Jest won the Highest Satisfaction award from [State of JS](https://2019.stateofjs.com/awards/). We are incredibly grateful for the support from the community, and hope we can build on this momentum to make 2020 even better! ## Plans for the future -- Jest’s configuration is vast and somewhat clunky - there is often _at least_ two ways of doing the same thing, oftentimes even more. For Jest 26 we hope to condense the config down, and make it more predictable. See this [issue](https://github.com/facebook/jest/issues/7185) for details. -- We also hope to be able to provide a proper programmatic API for running Jest, to make integration into IDEs and other tooling easier. Please see [this](https://github.com/facebook/jest/issues/5048) tracking issue. -- There’s been an open PR for adding Lolex as an implementation of Jest’s fake timers since December 2017. While we’re not adding it to any public APIs in Jest 25, support for it is technically included and you we're looking into how to expose this so people can test and experiment with it. Using it means you can mock out `Date` and other timer function Jest currently doesn’t touch. Note that this should be considered experimental, and a proper API support will come in a later release. Follow [this PR](https://github.com/facebook/jest/pull/7776) for the latest updates on the status. +- Jest’s configuration is vast and somewhat clunky - there is often _at least_ two ways of doing the same thing, oftentimes even more. For Jest 26 we hope to condense the config down, and make it more predictable. See this [issue](https://github.com/jestjs/jest/issues/7185) for details. +- We also hope to be able to provide a proper programmatic API for running Jest, to make integration into IDEs and other tooling easier. Please see [this](https://github.com/jestjs/jest/issues/5048) tracking issue. +- There’s been an open PR for adding Lolex as an implementation of Jest’s fake timers since December 2017. While we’re not adding it to any public APIs in Jest 25, support for it is technically included and you we're looking into how to expose this so people can test and experiment with it. Using it means you can mock out `Date` and other timer function Jest currently doesn’t touch. Note that this should be considered experimental, and a proper API support will come in a later release. Follow [this PR](https://github.com/jestjs/jest/pull/7776) for the latest updates on the status. Happy Jesting! 🃏 diff --git a/website/blog/2020-05-05-jest-26.md b/website/blog/2020-05-05-jest-26.md index d0b3f8cc1c75..e3eae8dc6280 100644 --- a/website/blog/2020-05-05-jest-26.md +++ b/website/blog/2020-05-05-jest-26.md @@ -11,11 +11,11 @@ We are now beginning to address this shortcoming and are working on reducing Jes -- `[expect, jest-mock, pretty-format]` Remove `ES5` build files with a new minimum of support of ES2015 (Node 8) which were only used for browser builds ([#9945](https://github.com/facebook/jest/pull/9945)) +- `[expect, jest-mock, pretty-format]` Remove `ES5` build files with a new minimum of support of ES2015 (Node 8) which were only used for browser builds ([#9945](https://github.com/jestjs/jest/pull/9945)) > **Migration**: With this change, we are pushing the responsibility to bundle the affected packages to the users, rather than Jest providing them out of the box, since they know their target environments best. If you want it back, we're open to shipping these as separate packages. PRs welcome! -- `[jest-config, jest-resolve]` Remove support for `browser` field ([#9943](https://github.com/facebook/jest/pull/9943)) +- `[jest-config, jest-resolve]` Remove support for `browser` field ([#9943](https://github.com/jestjs/jest/pull/9943)) > **Migration**: Install `browser-resolve` module and use the following configuration: @@ -34,7 +34,7 @@ We are now beginning to address this shortcoming and are working on reducing Jes module.exports = browserResolve.sync; ``` -- TypeScript definitions requires a minimum of TypeScript v3.8 ([#9823](https://github.com/facebook/jest/pull/9823)) +- TypeScript definitions requires a minimum of TypeScript v3.8 ([#9823](https://github.com/jestjs/jest/pull/9823)) With the above changes Jest 26 is now 4 MiB smaller than Jest 25.5.4 (53 → 49 MiB). Please keep in mind that many dependencies like Babel are likely already part of your project. Jest's own size was reduced by 1.2 MiB (4.3 -> 3.1 MiB). @@ -80,19 +80,19 @@ Caveats: ## Native ESM support -As mentioned in the [Jest 25 blog post](/blog/2020/01/21/jest-25#ecmascript-modules-support) we have been working on native support for ECMAScript Modules. It is not stable yet but it is ready to be tested. We'd love to hear your feedback and bug reports! For an overview of the current state you can check out [this issue](https://github.com/facebook/jest/issues/9430), or browse all issues with that label [ES Modules](https://github.com/facebook/jest/labels/ES%20Modules). +As mentioned in the [Jest 25 blog post](/blog/2020/01/21/jest-25#ecmascript-modules-support) we have been working on native support for ECMAScript Modules. It is not stable yet but it is ready to be tested. We'd love to hear your feedback and bug reports! For an overview of the current state you can check out [this issue](https://github.com/jestjs/jest/issues/9430), or browse all issues with that label [ES Modules](https://github.com/jestjs/jest/labels/ES%20Modules). ## Other Breaking Changes in Jest 26 -- Dropped support for Node 8 ([#9423](https://github.com/facebook/jest/pull/9423)) -- `[jest-environment-jsdom]` Upgrade `jsdom` to v16 ([#9606](https://github.com/facebook/jest/pull/9606)) -- `[jest-runtime]` Remove long-deprecated `require.requireActual` and `require.requireMock` methods ([#9854](https://github.com/facebook/jest/pull/9854)) -- `[jest-haste-map]` Removed `providesModuleNodeModules` ([#8535](https://github.com/facebook/jest/pull/8535)) -- `[jest-circus]` Fail tests if a test takes a done callback and have return values ([#9129](https://github.com/facebook/jest/pull/9129)) -- `[jest-circus]` Throw a proper error if a test / hooks is defined asynchronously ([#8096](https://github.com/facebook/jest/pull/8096)) +- Dropped support for Node 8 ([#9423](https://github.com/jestjs/jest/pull/9423)) +- `[jest-environment-jsdom]` Upgrade `jsdom` to v16 ([#9606](https://github.com/jestjs/jest/pull/9606)) +- `[jest-runtime]` Remove long-deprecated `require.requireActual` and `require.requireMock` methods ([#9854](https://github.com/jestjs/jest/pull/9854)) +- `[jest-haste-map]` Removed `providesModuleNodeModules` ([#8535](https://github.com/jestjs/jest/pull/8535)) +- `[jest-circus]` Fail tests if a test takes a done callback and have return values ([#9129](https://github.com/jestjs/jest/pull/9129)) +- `[jest-circus]` Throw a proper error if a test / hooks is defined asynchronously ([#8096](https://github.com/jestjs/jest/pull/8096)) ## Stay Safe -We are all currently experiencing an unprecedented time of uncertainty. If you are struggling financially, we would like to use [Jest’s Open Collective fund](https://opencollective.com/jest) to help new and existing contributors. We place [bounties on some issues](https://github.com/facebook/jest/issues?q=is%3Aissue+is%3Aopen+bounty+label%3A%22Has+Bounty%22) and are open to offering a bounty on any of our current open issues - you can mention that an issue should have a bounty in the issue or contact [@cpojer via private message on Twitter](https://twitter.com/cpojer). +We are all currently experiencing an unprecedented time of uncertainty. If you are struggling financially, we would like to use [Jest’s Open Collective fund](https://opencollective.com/jest) to help new and existing contributors. We place [bounties on some issues](https://github.com/jestjs/jest/issues?q=is%3Aissue+is%3Aopen+bounty+label%3A%22Has+Bounty%22) and are open to offering a bounty on any of our current open issues - you can mention that an issue should have a bounty in the issue or contact [@cpojer via private message on Twitter](https://twitter.com/cpojer). Please stay safe. diff --git a/website/blog/2021-03-09-jest-website-upgrade.md b/website/blog/2021-03-09-jest-website-upgrade.md index e68b3657e1a1..685250f7c77d 100644 --- a/website/blog/2021-03-09-jest-website-upgrade.md +++ b/website/blog/2021-03-09-jest-website-upgrade.md @@ -46,4 +46,4 @@ In localized pages, the edit button now links directly to Crowdin. Thanks to all the contributors that supported or reviewed this migration: [Simen](https://github.com/SimenB), [Orta](https://github.com/orta), [Joel](https://github.com/JoelMarcey), [Kristoffer](https://github.com/merceyz)... -Please report any problem on the [migration issue](https://github.com/facebook/jest/pull/11021). +Please report any problem on the [migration issue](https://github.com/jestjs/jest/pull/11021). diff --git a/website/blog/2021-05-25-jest-27.md b/website/blog/2021-05-25-jest-27.md index f53ebaf33867..01ac5b96108e 100644 --- a/website/blog/2021-05-25-jest-27.md +++ b/website/blog/2021-05-25-jest-27.md @@ -13,26 +13,26 @@ With the first major change of defaults since the [New Defaults for Jest](/blog/ ## Feature updates -Firstly, the interactive mode you may know from reviewing and updating failed snapshots can now also be used to **step through failed tests** one at a time. Credit goes to first-time contributor [@NullDivision](https://github.com/NullDivision) for [implementing](https://github.com/facebook/jest/pull/10858) this feature! +Firstly, the interactive mode you may know from reviewing and updating failed snapshots can now also be used to **step through failed tests** one at a time. Credit goes to first-time contributor [@NullDivision](https://github.com/NullDivision) for [implementing](https://github.com/jestjs/jest/pull/10858) this feature! ![Interactive failed test run](/img/blog/27-interactive-failures.png) -Speaking of snapshots, one of the more exciting features we've shipped in recent years are Inline Snapshots, which [landed](https://github.com/facebook/jest/pull/6380) in a minor release of Jest 23 almost three years ago. However, they came with the restriction that projects wanting to utilize them must be using [Prettier](https://prettier.io/) to format their code, because that's what Jest would use to make sure the file it writes the snapshots into remains properly formatted. -And so for most of these years, we've had a [pull request](https://github.com/facebook/jest/pull/7792) in the pipeline to eliminate this restriction and allow using **Inline Snapshots without Prettier**. It has amassed well above a hundred comments, not even taking into account PRs split out from it and landed first, and even changed owner once after the initial submission by another first-time contributor, [@mmkal](https://github.com/mmkal) under the hilarious working title 'Uglier Inline Snapshots'. With the stellar rise of Prettier in recent times, this improvement is now maybe less needed than back in 2018, but still, we know that feeling of getting into a project that does not use Prettier, and suddenly not being able to use inline snapshots anymore. Nevermore! +Speaking of snapshots, one of the more exciting features we've shipped in recent years are Inline Snapshots, which [landed](https://github.com/jestjs/jest/pull/6380) in a minor release of Jest 23 almost three years ago. However, they came with the restriction that projects wanting to utilize them must be using [Prettier](https://prettier.io/) to format their code, because that's what Jest would use to make sure the file it writes the snapshots into remains properly formatted. +And so for most of these years, we've had a [pull request](https://github.com/jestjs/jest/pull/7792) in the pipeline to eliminate this restriction and allow using **Inline Snapshots without Prettier**. It has amassed well above a hundred comments, not even taking into account PRs split out from it and landed first, and even changed owner once after the initial submission by another first-time contributor, [@mmkal](https://github.com/mmkal) under the hilarious working title 'Uglier Inline Snapshots'. With the stellar rise of Prettier in recent times, this improvement is now maybe less needed than back in 2018, but still, we know that feeling of getting into a project that does not use Prettier, and suddenly not being able to use inline snapshots anymore. Nevermore! The main reason why it took us so long to land this was, somewhat surprisingly, an out of memory error on our build pipeline. It turns out that the dependencies we load for each test file to perform the parsing, snapshot insertion, and printing do incur a significant time and memory overhead. -So with some [tricks](https://github.com/facebook/jest/issues/9898), we've **speed up the initialization per test file** by roughly 70% compared to Jest 26. Note that you will almost certainly not see this big of a performance improvement on your project—you would need a lot of test files that each run very quickly to best notice this, and the overhead when using a [JSDOM environment](/docs/configuration#testenvironment-string) dwarfs any such improvement. +So with some [tricks](https://github.com/jestjs/jest/issues/9898), we've **speed up the initialization per test file** by roughly 70% compared to Jest 26. Note that you will almost certainly not see this big of a performance improvement on your project—you would need a lot of test files that each run very quickly to best notice this, and the overhead when using a [JSDOM environment](/docs/configuration#testenvironment-string) dwarfs any such improvement. -In other news, the [native ESM support](https://github.com/facebook/jest/issues/9430) is progressing, but some major complexities, for instance around mocking, are still ahead of us, and we continue to observe the migration to ESM as a huge ecosystem effort, where Node and a lot of crucial tools and packages all have to rely on each other to deliver an overall compelling experience. -ESM support [for plugging modules into Jest](https://github.com/facebook/jest/issues/11167) is more advanced—custom runners, reporters, watch plugins, and many other modules can already be loaded as ES modules. +In other news, the [native ESM support](https://github.com/jestjs/jest/issues/9430) is progressing, but some major complexities, for instance around mocking, are still ahead of us, and we continue to observe the migration to ESM as a huge ecosystem effort, where Node and a lot of crucial tools and packages all have to rely on each other to deliver an overall compelling experience. +ESM support [for plugging modules into Jest](https://github.com/jestjs/jest/issues/11167) is more advanced—custom runners, reporters, watch plugins, and many other modules can already be loaded as ES modules. -We've also merged [a PR](https://github.com/facebook/jest/pull/9351) to be able to deal with test files symlinked into the test directory, a feature much wanted by users of [Bazel](https://bazel.build/). +We've also merged [a PR](https://github.com/jestjs/jest/pull/9351) to be able to deal with test files symlinked into the test directory, a feature much wanted by users of [Bazel](https://bazel.build/). -[Another PR](https://github.com/facebook/jest/issues/9504) enabled [`transform`s](/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object) to be asynchronous, a requirement to support transpilation through tools such as [esbuild](https://esbuild.github.io/), [Snowpack](https://www.snowpack.dev/), and [Vite](https://vitejs.dev/) effectively. +[Another PR](https://github.com/jestjs/jest/issues/9504) enabled [`transform`s](/docs/configuration#transform-objectstring-pathtotransformer--pathtotransformer-object) to be asynchronous, a requirement to support transpilation through tools such as [esbuild](https://esbuild.github.io/), [Snowpack](https://www.snowpack.dev/), and [Vite](https://vitejs.dev/) effectively. ## Flipping defaults -Up until now, if you were using Jest in its default configuration, you were—perhaps unknowingly—running some code forked many years ago from the test runner [Jasmine 2.0](https://jasmine.github.io/2.0/introduction) that provides test framework functions such as `describe`, `it`, and `beforeEach`. In 2017, [Aaron Abramov](https://github.com/aaronabramov) [initially wrote](https://github.com/facebook/jest/pull/3668) a **replacement for the Jasmine code** called `jest-circus`, meant to improve error messages, maintainability, and extensibility. +Up until now, if you were using Jest in its default configuration, you were—perhaps unknowingly—running some code forked many years ago from the test runner [Jasmine 2.0](https://jasmine.github.io/2.0/introduction) that provides test framework functions such as `describe`, `it`, and `beforeEach`. In 2017, [Aaron Abramov](https://github.com/aaronabramov) [initially wrote](https://github.com/jestjs/jest/pull/3668) a **replacement for the Jasmine code** called `jest-circus`, meant to improve error messages, maintainability, and extensibility. After years of large-scale use at Facebook and of course in Jest itself, as well as recent adoption in `create-react-app`, we are now confident that `jest-circus` is highly compatible with `jest-jasmine2` and should work in most environments with little to no migration work. There may be minor differences in execution order and strictness, but we expect no major upgrade difficulties other than for code relying on Jasmine-specific APIs such as `jasmine.getEnv()`. If you rely extensively on such APIs, you can opt back in to the Jasmine-based test runner by [configuring](/docs/configuration#testrunner-string) `"testRunner": "jest-jasmine2"`. Running tests in a [JSDOM environment](/docs/configuration#testenvironment-string) incurs a significant performance overhead. Because this was the default behavior of Jest unless otherwise configured up until now, users who are writing Node apps, for example, may not even know they are given an expensive DOM environment that they do not even need. @@ -51,7 +51,7 @@ We introduced a few more small breaking changes to help you avoid mistakes by di - calling `done` and returning a Promise may not be combined, - a `describe` block must not return anything, -and we [made some TypeScript types stricter](https://github.com/facebook/jest/pull/10512). +and we [made some TypeScript types stricter](https://github.com/jestjs/jest/pull/10512). Modules used in the following configuration options are now transformed like the rest of your code, which may be breaking if you relied on them being loaded as-is: @@ -72,6 +72,6 @@ A lot of Jest's packages have been migrated to use ESM-style exports (although t We dropped support for Node 13—but Jest always supports the _Current_ and all _LTS_ [Node versions](https://nodejs.org/en/about/releases/), and Jest 27 continues to support Node 10, which only recently became unmaintained. -As always, the full changelog and list of breaking changes can be [viewed here](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2700). +As always, the full changelog and list of breaking changes can be [viewed here](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2700). Finally, we'd like to thank the community for once again awarding Jest a sky-high satisfaction rating of 96% in the [State of JS 2020](https://2020.stateofjs.com/en-US/technologies/testing/) survey! Stay safe everyone, and we hope you continue to enjoy using Jest in the years and versions to come! 🃏 diff --git a/website/blog/2022-04-25-jest-28.md b/website/blog/2022-04-25-jest-28.md index 9b1995e9dfb8..1cbcbc329aa8 100644 --- a/website/blog/2022-04-25-jest-28.md +++ b/website/blog/2022-04-25-jest-28.md @@ -13,7 +13,7 @@ Additionally, as announced in the [Jest 27 blog post](/blog/2021/05/25/jest-27) ## Breaking changes -The list of breaking changes is long (and can be seen fully in the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2800)), but for migration purposes, we've also written [a guide](/docs/28.x/upgrading-to-jest28) you can follow. Hopefully this makes the upgrade experience as frictionless as possible! +The list of breaking changes is long (and can be seen fully in the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2800)), but for migration purposes, we've also written [a guide](/docs/28.x/upgrading-to-jest28) you can follow. Hopefully this makes the upgrade experience as frictionless as possible! Main breaking changes likely to impact your migration are dropped support for Node 10 and 15 (but _not_ Node 12, which will be EOL in a few days) and some renamed configuration options. @@ -120,7 +120,7 @@ If you use Jest with TypeScript, either in your tests or when writing plugins su ### `expect` -When using `expect`'s own types (either directly, or via `import {expect} from '@jest/globals'`), it's now finally possible to add custom matchers. See our [example](https://github.com/facebook/jest/tree/main/examples/expect-extend) for how to do this. +When using `expect`'s own types (either directly, or via `import {expect} from '@jest/globals'`), it's now finally possible to add custom matchers. See our [example](https://github.com/jestjs/jest/tree/main/examples/expect-extend) for how to do this. ### Custom plugins diff --git a/website/blog/2022-08-25-jest-29.md b/website/blog/2022-08-25-jest-29.md index 9ab4001bc644..3c13a6567018 100644 --- a/website/blog/2022-08-25-jest-29.md +++ b/website/blog/2022-08-25-jest-29.md @@ -25,6 +25,6 @@ The only breaking changes that should be noticeable are: There are certain changes to the types exposed by Jest, but probably (hopefully!) nothing that should impede the upgrade. Please see the [upgrade guide](/docs/upgrading-to-jest29) for more details. -That's it for breaking changes! Hopefully this means the upgrade path from Jest 28 is smooth. Please see the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for other changes. +That's it for breaking changes! Hopefully this means the upgrade path from Jest 28 is smooth. Please see the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for other changes. Thanks for reading, and happy Jesting! 🃏 diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js index bdd780db9fe6..14649b3574de 100644 --- a/website/docusaurus.config.js +++ b/website/docusaurus.config.js @@ -56,7 +56,7 @@ const config = { if (translation !== 'en') { return `https://crowdin.com/project/jest-v2/${translation}`; } - return `https://github.com/facebook/jest/edit/main/website/${versionDocsDirPath}/${docPath}`; + return `https://github.com/jestjs/jest/edit/main/website/${versionDocsDirPath}/${docPath}`; }, path: '../docs', sidebarPath: path.resolve(__dirname, './sidebars.json'), @@ -67,7 +67,7 @@ const config = { }, blog: { showReadingTime: true, - editUrl: 'https://github.com/facebook/jest/tree/main/website/', + editUrl: 'https://github.com/jestjs/jest/tree/main/website/', }, theme: { customCss: [ @@ -214,7 +214,7 @@ const config = { {to: 'blog', label: 'Blog', position: 'right'}, {type: 'localeDropdown', position: 'right'}, { - href: 'https://github.com/facebook/jest', + href: 'https://github.com/jestjs/jest', position: 'right', className: 'header-github-link', 'aria-label': 'GitHub repository', @@ -272,7 +272,7 @@ const config = { }, { label: 'GitHub', - href: 'https://github.com/facebook/jest', + href: 'https://github.com/jestjs/jest', }, { label: 'Twitter', diff --git a/website/src/pages/help.js b/website/src/pages/help.js index 257ef260f1d8..161037e47d51 100755 --- a/website/src/pages/help.js +++ b/website/src/pages/help.js @@ -45,7 +45,7 @@ class Help extends React.Component { {`Find out what's new with Jest. - Follow [Jest](https://twitter.com/jestjs_) on Twitter. - Subscribe to the [Jest blog](/blog/). -- Look at the [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md).`} +- Look at the [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md).`} ), title: Stay up to date, diff --git a/website/src/pages/index.js b/website/src/pages/index.js index b23871cdee72..c189524186da 100755 --- a/website/src/pages/index.js +++ b/website/src/pages/index.js @@ -43,7 +43,7 @@ function GitHubStarButton() { return (
diff --git a/website/src/pages/versions.js b/website/src/pages/versions.js index f249ca15e5ec..60c28373af81 100644 --- a/website/src/pages/versions.js +++ b/website/src/pages/versions.js @@ -36,7 +36,7 @@ export default function VersionsPage() { Documentation - + Release Notes @@ -55,7 +55,7 @@ export default function VersionsPage() { Documentation - Source Code + Source Code diff --git a/website/static/_redirects b/website/static/_redirects index 11a3b2d954d3..fc484ab059a0 100644 --- a/website/static/_redirects +++ b/website/static/_redirects @@ -3,7 +3,7 @@ # Initially used to handle the Docusaurus v1-v2 migration url changes # https://github.com/jest-website-migration/jest -# https://github.com/facebook/jest/pull/11021 +# https://github.com/jestjs/jest/pull/11021 /en/* /:splat diff --git a/website/users.json b/website/users.json index 1c4ef994e54a..e23faca38721 100644 --- a/website/users.json +++ b/website/users.json @@ -1,5 +1,5 @@ { - "editUrl": "https://github.com/facebook/jest/edit/main/website/users.json", + "editUrl": "https://github.com/jestjs/jest/edit/main/website/users.json", "users": [ { "caption": "Facebook", diff --git a/website/versioned_docs/version-25.x/Configuration.md b/website/versioned_docs/version-25.x/Configuration.md index ac955a96935d..9d85a780abf7 100644 --- a/website/versioned_docs/version-25.x/Configuration.md +++ b/website/versioned_docs/version-25.x/Configuration.md @@ -243,7 +243,7 @@ Additional options can be passed using the tuple form. For example, you may hide } ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -446,7 +446,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) object as a parameter. +This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) object as a parameter. :::info @@ -477,7 +477,7 @@ module.exports = async function () { Default: `undefined` -This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) object as a parameter. +This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) object as a parameter. :::info @@ -730,7 +730,7 @@ Additionally, custom reporters can be configured by passing an `options` object } ``` -Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/facebook/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) and reporter options as constructor arguments: +Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) and reporter options as constructor arguments: Example reporter: @@ -765,7 +765,7 @@ class MyCustomReporter { } ``` -For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts) +For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts) ### `resetMocks` \[boolean] @@ -858,7 +858,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -997,7 +997,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1022,7 +1022,7 @@ test('use jsdom in this test file', () => { You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -1247,7 +1247,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -1265,7 +1265,7 @@ const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -1304,7 +1304,7 @@ Setting this value to `legacy` or `fake` enables fake timers for all tests by de Default: `{"^.+\\.[jt]sx?$": "babel-jest"}` -A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/facebook/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). +A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/jestjs/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). Examples of such compilers include: @@ -1323,7 +1323,7 @@ A transformer is only run once per file unless the file has changed. During the :::note -When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). +When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). ::: diff --git a/website/versioned_docs/version-25.x/ECMAScriptModules.md b/website/versioned_docs/version-25.x/ECMAScriptModules.md index 9ac5406f52f7..61f7fbbbff8a 100644 --- a/website/versioned_docs/version-25.x/ECMAScriptModules.md +++ b/website/versioned_docs/version-25.x/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -72,4 +72,4 @@ const exported = await import('./main.cjs'); // etc. ``` -Please note that we currently don't support `jest.mock` in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +Please note that we currently don't support `jest.mock` in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. diff --git a/website/versioned_docs/version-25.x/ExpectAPI.md b/website/versioned_docs/version-25.x/ExpectAPI.md index 323d257dc76c..f4432aa4d876 100644 --- a/website/versioned_docs/version-25.x/ExpectAPI.md +++ b/website/versioned_docs/version-25.x/ExpectAPI.md @@ -182,7 +182,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-25.x/JestObjectAPI.md b/website/versioned_docs/version-25.x/JestObjectAPI.md index 0590a21cbd8d..3e2067dfcddc 100644 --- a/website/versioned_docs/version-25.x/JestObjectAPI.md +++ b/website/versioned_docs/version-25.x/JestObjectAPI.md @@ -701,7 +701,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-25.x/JestPlatform.md b/website/versioned_docs/version-25.x/JestPlatform.md index 1cc478cbacc7..298f5cf64600 100644 --- a/website/versioned_docs/version-25.x/JestPlatform.md +++ b/website/versioned_docs/version-25.x/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-25.x/ManualMocks.md b/website/versioned_docs/version-25.x/ManualMocks.md index 39368f2a3a02..62e80a9b9079 100644 --- a/website/versioned_docs/version-25.x/ManualMocks.md +++ b/website/versioned_docs/version-25.x/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.genMockFromModule`](JestObjectAPI.md#jes To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-25.x/MockFunctionAPI.md b/website/versioned_docs/version-25.x/MockFunctionAPI.md index 3cbc6e53f6ad..9d591d222426 100644 --- a/website/versioned_docs/version-25.x/MockFunctionAPI.md +++ b/website/versioned_docs/version-25.x/MockFunctionAPI.md @@ -356,7 +356,7 @@ If you are using [Create React App](https://create-react-app.dev) then the [Type Otherwise, please see our [Getting Started](GettingStarted.md#using-typescript) guide for to get setup with TypeScript. -You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/facebook/jest/tree/main/examples/typescript). +You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/jestjs/jest/tree/main/examples/typescript). ### `jest.MockedFunction` diff --git a/website/versioned_docs/version-25.x/MoreResources.md b/website/versioned_docs/version-25.x/MoreResources.md index 500482e69388..c55840f82415 100644 --- a/website/versioned_docs/version-25.x/MoreResources.md +++ b/website/versioned_docs/version-25.x/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-25.x/Puppeteer.md b/website/versioned_docs/version-25.x/Puppeteer.md index c1aafd6ba637..a05edd1fc702 100644 --- a/website/versioned_docs/version-25.x/Puppeteer.md +++ b/website/versioned_docs/version-25.x/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-25.x/SnapshotTesting.md b/website/versioned_docs/version-25.x/SnapshotTesting.md index 1dabee33f66a..952ae6a508c2 100644 --- a/website/versioned_docs/version-25.x/SnapshotTesting.md +++ b/website/versioned_docs/version-25.x/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import React from 'react'; @@ -24,7 +24,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -39,7 +39,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -85,7 +85,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -245,7 +245,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -305,7 +305,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-25.x/TimerMocks.md b/website/versioned_docs/version-25.x/TimerMocks.md index d7d4e67c7b12..58794c6a190a 100644 --- a/website/versioned_docs/version-25.x/TimerMocks.md +++ b/website/versioned_docs/version-25.x/TimerMocks.md @@ -182,4 +182,4 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/main/examples/timer). +The code for this example is available at [examples/timer](https://github.com/jestjs/jest/tree/main/examples/timer). diff --git a/website/versioned_docs/version-25.x/Troubleshooting.md b/website/versioned_docs/version-25.x/Troubleshooting.md index 37a217b011a2..5efe7e9efd24 100644 --- a/website/versioned_docs/version-25.x/Troubleshooting.md +++ b/website/versioned_docs/version-25.x/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-25.x/TutorialAsync.md b/website/versioned_docs/version-25.x/TutorialAsync.md index f9bbe7f6713f..d7f712fd9398 100644 --- a/website/versioned_docs/version-25.x/TutorialAsync.md +++ b/website/versioned_docs/version-25.x/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-25.x/TutorialReact.md b/website/versioned_docs/version-25.x/TutorialReact.md index 4f39f70189c1..65cce15c0bbf 100644 --- a/website/versioned_docs/version-25.x/TutorialReact.md +++ b/website/versioned_docs/version-25.x/TutorialReact.md @@ -162,7 +162,7 @@ exports[`Link changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 @@ -251,7 +251,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-25.x/TutorialReactNative.md b/website/versioned_docs/version-25.x/TutorialReactNative.md index 89da13d6e59c..8804c38a1b20 100644 --- a/website/versioned_docs/version-25.x/TutorialReactNative.md +++ b/website/versioned_docs/version-25.x/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-25.x/TutorialjQuery.md b/website/versioned_docs/version-25.x/TutorialjQuery.md index d6f32d3c74f6..e2bc3b3969cb 100644 --- a/website/versioned_docs/version-25.x/TutorialjQuery.md +++ b/website/versioned_docs/version-25.x/TutorialjQuery.md @@ -63,4 +63,4 @@ The function being tested adds an event listener on the `#button` DOM element, s We are mocking `fetchCurrentUser.js` so that our test doesn't make a real network request but instead resolves to mock data locally. This ensures that our test can complete in milliseconds rather than seconds and guarantees a fast unit test iteration speed. -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-25.x/WatchPlugins.md b/website/versioned_docs/version-25.x/WatchPlugins.md index f9c42462c9b9..13b53cd301c6 100644 --- a/website/versioned_docs/version-25.x/WatchPlugins.md +++ b/website/versioned_docs/version-25.x/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-26.x/Configuration.md b/website/versioned_docs/version-26.x/Configuration.md index a3e5c2a5b331..3859d39f9fe3 100644 --- a/website/versioned_docs/version-26.x/Configuration.md +++ b/website/versioned_docs/version-26.x/Configuration.md @@ -260,7 +260,7 @@ Additional options can be passed using the tuple form. For example, you may hide } ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -463,7 +463,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) object as a parameter. +This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) object as a parameter. :::info @@ -494,7 +494,7 @@ module.exports = async function () { Default: `undefined` -This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) object as a parameter. +This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) object as a parameter. :::info @@ -769,7 +769,7 @@ Additionally, custom reporters can be configured by passing an `options` object } ``` -Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) and reporter options as constructor arguments: +Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/jestjs/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) and reporter options as constructor arguments: Example reporter: @@ -804,7 +804,7 @@ class MyCustomReporter { } ``` -For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts) +For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts) ### `resetMocks` \[boolean] @@ -944,7 +944,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1083,7 +1083,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1108,7 +1108,7 @@ test('use jsdom in this test file', () => { You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -1333,7 +1333,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -1351,7 +1351,7 @@ const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -1392,7 +1392,7 @@ If the value is `modern`, [`@sinonjs/fake-timers`](https://github.com/sinonjs/fa Default: `{"\\.[jt]sx?$": "babel-jest"}` -A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/facebook/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). +A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/jestjs/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). Examples of such compilers include: @@ -1411,7 +1411,7 @@ A transformer is only run once per file unless the file has changed. During the :::note -When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). +When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). ::: diff --git a/website/versioned_docs/version-26.x/ECMAScriptModules.md b/website/versioned_docs/version-26.x/ECMAScriptModules.md index 9ac5406f52f7..61f7fbbbff8a 100644 --- a/website/versioned_docs/version-26.x/ECMAScriptModules.md +++ b/website/versioned_docs/version-26.x/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -72,4 +72,4 @@ const exported = await import('./main.cjs'); // etc. ``` -Please note that we currently don't support `jest.mock` in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +Please note that we currently don't support `jest.mock` in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. diff --git a/website/versioned_docs/version-26.x/ExpectAPI.md b/website/versioned_docs/version-26.x/ExpectAPI.md index 323d257dc76c..f4432aa4d876 100644 --- a/website/versioned_docs/version-26.x/ExpectAPI.md +++ b/website/versioned_docs/version-26.x/ExpectAPI.md @@ -182,7 +182,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-26.x/GlobalAPI.md b/website/versioned_docs/version-26.x/GlobalAPI.md index 7438f00993b8..c834e5fffc53 100644 --- a/website/versioned_docs/version-26.x/GlobalAPI.md +++ b/website/versioned_docs/version-26.x/GlobalAPI.md @@ -477,7 +477,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: diff --git a/website/versioned_docs/version-26.x/JestObjectAPI.md b/website/versioned_docs/version-26.x/JestObjectAPI.md index bce3a5dddf6a..17a2206ff200 100644 --- a/website/versioned_docs/version-26.x/JestObjectAPI.md +++ b/website/versioned_docs/version-26.x/JestObjectAPI.md @@ -735,7 +735,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-26.x/JestPlatform.md b/website/versioned_docs/version-26.x/JestPlatform.md index 429b1172c8bb..208976e52f5b 100644 --- a/website/versioned_docs/version-26.x/JestPlatform.md +++ b/website/versioned_docs/version-26.x/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-26.x/ManualMocks.md b/website/versioned_docs/version-26.x/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-26.x/ManualMocks.md +++ b/website/versioned_docs/version-26.x/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-26.x/MockFunctionAPI.md b/website/versioned_docs/version-26.x/MockFunctionAPI.md index 3cbc6e53f6ad..9d591d222426 100644 --- a/website/versioned_docs/version-26.x/MockFunctionAPI.md +++ b/website/versioned_docs/version-26.x/MockFunctionAPI.md @@ -356,7 +356,7 @@ If you are using [Create React App](https://create-react-app.dev) then the [Type Otherwise, please see our [Getting Started](GettingStarted.md#using-typescript) guide for to get setup with TypeScript. -You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/facebook/jest/tree/main/examples/typescript). +You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/jestjs/jest/tree/main/examples/typescript). ### `jest.MockedFunction` diff --git a/website/versioned_docs/version-26.x/MoreResources.md b/website/versioned_docs/version-26.x/MoreResources.md index 500482e69388..c55840f82415 100644 --- a/website/versioned_docs/version-26.x/MoreResources.md +++ b/website/versioned_docs/version-26.x/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-26.x/Puppeteer.md b/website/versioned_docs/version-26.x/Puppeteer.md index c1aafd6ba637..a05edd1fc702 100644 --- a/website/versioned_docs/version-26.x/Puppeteer.md +++ b/website/versioned_docs/version-26.x/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-26.x/SnapshotTesting.md b/website/versioned_docs/version-26.x/SnapshotTesting.md index 1dabee33f66a..952ae6a508c2 100644 --- a/website/versioned_docs/version-26.x/SnapshotTesting.md +++ b/website/versioned_docs/version-26.x/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import React from 'react'; @@ -24,7 +24,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -39,7 +39,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -85,7 +85,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -245,7 +245,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -305,7 +305,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-26.x/TimerMocks.md b/website/versioned_docs/version-26.x/TimerMocks.md index 81e9f5e120a8..8ed1ce179a28 100644 --- a/website/versioned_docs/version-26.x/TimerMocks.md +++ b/website/versioned_docs/version-26.x/TimerMocks.md @@ -166,4 +166,4 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/main/examples/timer). +The code for this example is available at [examples/timer](https://github.com/jestjs/jest/tree/main/examples/timer). diff --git a/website/versioned_docs/version-26.x/Troubleshooting.md b/website/versioned_docs/version-26.x/Troubleshooting.md index 37a217b011a2..5efe7e9efd24 100644 --- a/website/versioned_docs/version-26.x/Troubleshooting.md +++ b/website/versioned_docs/version-26.x/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-26.x/TutorialAsync.md b/website/versioned_docs/version-26.x/TutorialAsync.md index f9bbe7f6713f..d7f712fd9398 100644 --- a/website/versioned_docs/version-26.x/TutorialAsync.md +++ b/website/versioned_docs/version-26.x/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-26.x/TutorialReact.md b/website/versioned_docs/version-26.x/TutorialReact.md index 4f39f70189c1..65cce15c0bbf 100644 --- a/website/versioned_docs/version-26.x/TutorialReact.md +++ b/website/versioned_docs/version-26.x/TutorialReact.md @@ -162,7 +162,7 @@ exports[`Link changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 @@ -251,7 +251,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-26.x/TutorialReactNative.md b/website/versioned_docs/version-26.x/TutorialReactNative.md index 89da13d6e59c..8804c38a1b20 100644 --- a/website/versioned_docs/version-26.x/TutorialReactNative.md +++ b/website/versioned_docs/version-26.x/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-26.x/TutorialjQuery.md b/website/versioned_docs/version-26.x/TutorialjQuery.md index d6f32d3c74f6..e2bc3b3969cb 100644 --- a/website/versioned_docs/version-26.x/TutorialjQuery.md +++ b/website/versioned_docs/version-26.x/TutorialjQuery.md @@ -63,4 +63,4 @@ The function being tested adds an event listener on the `#button` DOM element, s We are mocking `fetchCurrentUser.js` so that our test doesn't make a real network request but instead resolves to mock data locally. This ensures that our test can complete in milliseconds rather than seconds and guarantees a fast unit test iteration speed. -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-26.x/WatchPlugins.md b/website/versioned_docs/version-26.x/WatchPlugins.md index fa54ce13ff0c..892017c9ab73 100644 --- a/website/versioned_docs/version-26.x/WatchPlugins.md +++ b/website/versioned_docs/version-26.x/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L255-L321): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-27.x/CodeTransformation.md b/website/versioned_docs/version-27.x/CodeTransformation.md index bf97210d3284..28f5ae772231 100644 --- a/website/versioned_docs/version-27.x/CodeTransformation.md +++ b/website/versioned_docs/version-27.x/CodeTransformation.md @@ -128,7 +128,7 @@ type TransformedSource = | {code: string; map?: RawSourceMap | string | null} | string; -// Config.ProjectConfig can be seen in code [here](https://github.com/facebook/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L323) +// Config.ProjectConfig can be seen in code [here](https://github.com/jestjs/jest/blob/v26.6.3/packages/jest-types/src/Config.ts#L323) // RawSourceMap comes from [`source-map`](https://github.com/mozilla/source-map/blob/0.6.1/source-map.d.ts#L6-L12) ``` diff --git a/website/versioned_docs/version-27.x/Configuration.md b/website/versioned_docs/version-27.x/Configuration.md index c9d0653cc23d..7c14c051dc67 100644 --- a/website/versioned_docs/version-27.x/Configuration.md +++ b/website/versioned_docs/version-27.x/Configuration.md @@ -260,7 +260,7 @@ Additional options can be passed using the tuple form. For example, you may hide } ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -484,7 +484,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) object as a parameter. +This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) object as a parameter. :::info @@ -515,7 +515,7 @@ module.exports = async function () { Default: `undefined` -This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) object as a parameter. +This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) object as a parameter. :::info @@ -800,7 +800,7 @@ Additionally, custom reporters can be configured by passing an `options` object } ``` -Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/facebook/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) and reporter options as constructor arguments: +Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/jestjs/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) and reporter options as constructor arguments: Example reporter: @@ -835,7 +835,7 @@ class MyCustomReporter { } ``` -For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts) +For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts) ### `resetMocks` \[boolean] @@ -979,7 +979,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1153,7 +1153,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1178,7 +1178,7 @@ test('use jsdom in this test file', () => { You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -1403,7 +1403,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -1421,7 +1421,7 @@ const Sequencer = require('@jest/test-sequencer').default; class CustomSequencer extends Sequencer { sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -1462,7 +1462,7 @@ If the value is `legacy`, the old implementation will be used as implementation Default: `{"\\.[jt]sx?$": "babel-jest"}` -A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/facebook/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). +A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/jestjs/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). Examples of such compilers include: @@ -1480,7 +1480,7 @@ A transformer is only run once per file unless the file has changed. During the :::note -When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). +When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). ::: diff --git a/website/versioned_docs/version-27.x/ECMAScriptModules.md b/website/versioned_docs/version-27.x/ECMAScriptModules.md index 118a2140bcff..896317f63565 100644 --- a/website/versioned_docs/version-27.x/ECMAScriptModules.md +++ b/website/versioned_docs/version-27.x/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -41,7 +41,7 @@ jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-27.x/ExpectAPI.md b/website/versioned_docs/version-27.x/ExpectAPI.md index da567b7ac4cb..ede9cad336f6 100644 --- a/website/versioned_docs/version-27.x/ExpectAPI.md +++ b/website/versioned_docs/version-27.x/ExpectAPI.md @@ -182,7 +182,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-27.x/GlobalAPI.md b/website/versioned_docs/version-27.x/GlobalAPI.md index bb5d1c4311a3..8fffd57e026a 100644 --- a/website/versioned_docs/version-27.x/GlobalAPI.md +++ b/website/versioned_docs/version-27.x/GlobalAPI.md @@ -501,7 +501,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: diff --git a/website/versioned_docs/version-27.x/JestObjectAPI.md b/website/versioned_docs/version-27.x/JestObjectAPI.md index 25a665116f18..f7873daaae82 100644 --- a/website/versioned_docs/version-27.x/JestObjectAPI.md +++ b/website/versioned_docs/version-27.x/JestObjectAPI.md @@ -781,7 +781,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-27.x/JestPlatform.md b/website/versioned_docs/version-27.x/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-27.x/JestPlatform.md +++ b/website/versioned_docs/version-27.x/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-27.x/ManualMocks.md b/website/versioned_docs/version-27.x/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-27.x/ManualMocks.md +++ b/website/versioned_docs/version-27.x/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-27.x/MockFunctionAPI.md b/website/versioned_docs/version-27.x/MockFunctionAPI.md index a5eb6f45a7de..c5d70b042f6e 100644 --- a/website/versioned_docs/version-27.x/MockFunctionAPI.md +++ b/website/versioned_docs/version-27.x/MockFunctionAPI.md @@ -366,7 +366,7 @@ If you are using [Create React App](https://create-react-app.dev) then the [Type Otherwise, please see our [Getting Started](GettingStarted.md#using-typescript) guide for to get setup with TypeScript. -You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/facebook/jest/tree/main/examples/typescript). +You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/jestjs/jest/tree/main/examples/typescript). ### `jest.MockedFunction` diff --git a/website/versioned_docs/version-27.x/MoreResources.md b/website/versioned_docs/version-27.x/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-27.x/MoreResources.md +++ b/website/versioned_docs/version-27.x/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-27.x/Puppeteer.md b/website/versioned_docs/version-27.x/Puppeteer.md index 7d4b6576c86b..76493ab6ada5 100644 --- a/website/versioned_docs/version-27.x/Puppeteer.md +++ b/website/versioned_docs/version-27.x/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-27.x/SnapshotTesting.md b/website/versioned_docs/version-27.x/SnapshotTesting.md index f7cad46f049f..4ca5ba308a2a 100644 --- a/website/versioned_docs/version-27.x/SnapshotTesting.md +++ b/website/versioned_docs/version-27.x/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import React from 'react'; @@ -24,7 +24,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -39,7 +39,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -85,7 +85,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -237,7 +237,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -297,7 +297,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-27.x/TimerMocks.md b/website/versioned_docs/version-27.x/TimerMocks.md index 6f811abee6b4..6a8d1018dd01 100644 --- a/website/versioned_docs/version-27.x/TimerMocks.md +++ b/website/versioned_docs/version-27.x/TimerMocks.md @@ -182,4 +182,4 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/main/examples/timer). +The code for this example is available at [examples/timer](https://github.com/jestjs/jest/tree/main/examples/timer). diff --git a/website/versioned_docs/version-27.x/Troubleshooting.md b/website/versioned_docs/version-27.x/Troubleshooting.md index 37a217b011a2..5efe7e9efd24 100644 --- a/website/versioned_docs/version-27.x/Troubleshooting.md +++ b/website/versioned_docs/version-27.x/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-27.x/TutorialAsync.md b/website/versioned_docs/version-27.x/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-27.x/TutorialAsync.md +++ b/website/versioned_docs/version-27.x/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-27.x/TutorialReact.md b/website/versioned_docs/version-27.x/TutorialReact.md index 7dc4e17818a8..b19e61d49b75 100644 --- a/website/versioned_docs/version-27.x/TutorialReact.md +++ b/website/versioned_docs/version-27.x/TutorialReact.md @@ -162,7 +162,7 @@ exports[`Link changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 @@ -251,7 +251,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-27.x/TutorialReactNative.md b/website/versioned_docs/version-27.x/TutorialReactNative.md index c5a31d55a5bb..15b4537243f6 100644 --- a/website/versioned_docs/version-27.x/TutorialReactNative.md +++ b/website/versioned_docs/version-27.x/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-27.x/TutorialjQuery.md b/website/versioned_docs/version-27.x/TutorialjQuery.md index d6f32d3c74f6..e2bc3b3969cb 100644 --- a/website/versioned_docs/version-27.x/TutorialjQuery.md +++ b/website/versioned_docs/version-27.x/TutorialjQuery.md @@ -63,4 +63,4 @@ The function being tested adds an event listener on the `#button` DOM element, s We are mocking `fetchCurrentUser.js` so that our test doesn't make a real network request but instead resolves to mock data locally. This ensures that our test can complete in milliseconds rather than seconds and guarantees a fast unit test iteration speed. -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-27.x/WatchPlugins.md b/website/versioned_docs/version-27.x/WatchPlugins.md index d295bb248d68..cedcfdf5f0bf 100644 --- a/website/versioned_docs/version-27.x/WatchPlugins.md +++ b/website/versioned_docs/version-27.x/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v27.5.1/packages/jest-types/src/Config.ts#L288-L350): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-28.x/CodeTransformation.md b/website/versioned_docs/version-28.x/CodeTransformation.md index ab59f9cc03a1..582923eeb3c0 100644 --- a/website/versioned_docs/version-28.x/CodeTransformation.md +++ b/website/versioned_docs/version-28.x/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-28.x/Configuration.md b/website/versioned_docs/version-28.x/Configuration.md index c09915f6b902..ed5e5936cf8a 100644 --- a/website/versioned_docs/version-28.x/Configuration.md +++ b/website/versioned_docs/version-28.x/Configuration.md @@ -260,7 +260,7 @@ Additional options can be passed using the tuple form. For example, you may hide } ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -565,7 +565,7 @@ Note that, if you specify a global reference value (like an object or array) her Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L424-L480). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L424-L480). :::info @@ -600,7 +600,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L424-L480). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L424-L480). :::info @@ -910,7 +910,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1077,7 +1077,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1286,7 +1286,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1309,9 +1309,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L424-L480) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L424-L480) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -1564,7 +1564,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -1606,7 +1606,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -1635,7 +1635,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. diff --git a/website/versioned_docs/version-28.x/ECMAScriptModules.md b/website/versioned_docs/version-28.x/ECMAScriptModules.md index 38e00b7ab514..75cbc17709ee 100644 --- a/website/versioned_docs/version-28.x/ECMAScriptModules.md +++ b/website/versioned_docs/version-28.x/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -46,7 +46,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-28.x/ExpectAPI.md b/website/versioned_docs/version-28.x/ExpectAPI.md index da567b7ac4cb..ede9cad336f6 100644 --- a/website/versioned_docs/version-28.x/ExpectAPI.md +++ b/website/versioned_docs/version-28.x/ExpectAPI.md @@ -182,7 +182,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-28.x/GlobalAPI.md b/website/versioned_docs/version-28.x/GlobalAPI.md index 22384d8a558e..c0a8a4147f20 100644 --- a/website/versioned_docs/version-28.x/GlobalAPI.md +++ b/website/versioned_docs/version-28.x/GlobalAPI.md @@ -501,7 +501,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -747,7 +747,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -779,7 +779,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -791,7 +791,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-28.x/JestObjectAPI.md b/website/versioned_docs/version-28.x/JestObjectAPI.md index 2d40fe820a86..f07b6fc7a740 100644 --- a/website/versioned_docs/version-28.x/JestObjectAPI.md +++ b/website/versioned_docs/version-28.x/JestObjectAPI.md @@ -891,7 +891,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-28.x/JestPlatform.md b/website/versioned_docs/version-28.x/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-28.x/JestPlatform.md +++ b/website/versioned_docs/version-28.x/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-28.x/ManualMocks.md b/website/versioned_docs/version-28.x/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-28.x/ManualMocks.md +++ b/website/versioned_docs/version-28.x/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-28.x/MoreResources.md b/website/versioned_docs/version-28.x/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-28.x/MoreResources.md +++ b/website/versioned_docs/version-28.x/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-28.x/Puppeteer.md b/website/versioned_docs/version-28.x/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-28.x/Puppeteer.md +++ b/website/versioned_docs/version-28.x/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-28.x/SnapshotTesting.md b/website/versioned_docs/version-28.x/SnapshotTesting.md index dfbe33c25995..7888ad1004e7 100644 --- a/website/versioned_docs/version-28.x/SnapshotTesting.md +++ b/website/versioned_docs/version-28.x/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-28.x/Troubleshooting.md b/website/versioned_docs/version-28.x/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-28.x/Troubleshooting.md +++ b/website/versioned_docs/version-28.x/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-28.x/TutorialAsync.md b/website/versioned_docs/version-28.x/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-28.x/TutorialAsync.md +++ b/website/versioned_docs/version-28.x/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-28.x/TutorialReact.md b/website/versioned_docs/version-28.x/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-28.x/TutorialReact.md +++ b/website/versioned_docs/version-28.x/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-28.x/TutorialReactNative.md b/website/versioned_docs/version-28.x/TutorialReactNative.md index c5a31d55a5bb..15b4537243f6 100644 --- a/website/versioned_docs/version-28.x/TutorialReactNative.md +++ b/website/versioned_docs/version-28.x/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-28.x/TutorialjQuery.md b/website/versioned_docs/version-28.x/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-28.x/TutorialjQuery.md +++ b/website/versioned_docs/version-28.x/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-28.x/UpgradingToJest28.md b/website/versioned_docs/version-28.x/UpgradingToJest28.md index e529cab06118..6a9de0206775 100644 --- a/website/versioned_docs/version-28.x/UpgradingToJest28.md +++ b/website/versioned_docs/version-28.x/UpgradingToJest28.md @@ -7,7 +7,7 @@ Upgrading Jest from v27 to v28? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2800) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2800) for the full list of changes. ::: @@ -129,7 +129,7 @@ If legacy fake timers are enabled in Jest config file, but you would like to dis ### Custom Environment -The constructor of [test environment](Configuration.md#testenvironment-string) class now receives an object with Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and `projectConfig` as its first argument. The second argument is now mandatory. +The constructor of [test environment](Configuration.md#testenvironment-string) class now receives an object with Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422) and `projectConfig` as its first argument. The second argument is now mandatory. ```diff class CustomEnvironment extends NodeEnvironment { diff --git a/website/versioned_docs/version-28.x/WatchPlugins.md b/website/versioned_docs/version-28.x/WatchPlugins.md index eeeab1d2c8b7..680e6af59bb2 100644 --- a/website/versioned_docs/version-28.x/WatchPlugins.md +++ b/website/versioned_docs/version-28.x/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v28.1.3/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.0/CodeTransformation.md b/website/versioned_docs/version-29.0/CodeTransformation.md index 6a7bdebd4799..1bf6dc48ba6f 100644 --- a/website/versioned_docs/version-29.0/CodeTransformation.md +++ b/website/versioned_docs/version-29.0/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.0/Configuration.md b/website/versioned_docs/version-29.0/Configuration.md index 2cc113521b12..83acd74cd3bc 100644 --- a/website/versioned_docs/version-29.0/Configuration.md +++ b/website/versioned_docs/version-29.0/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L421-L478). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L421-L478). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L421-L478). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L421-L478). :::info @@ -1330,7 +1330,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1512,7 +1512,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1760,7 +1760,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1783,9 +1783,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L421-L478) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L421-L478) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2072,7 +2072,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2112,7 +2112,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2154,7 +2154,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2369,7 +2369,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2387,7 +2387,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.0/ECMAScriptModules.md b/website/versioned_docs/version-29.0/ECMAScriptModules.md index 38e00b7ab514..75cbc17709ee 100644 --- a/website/versioned_docs/version-29.0/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.0/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -46,7 +46,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.0/ExpectAPI.md b/website/versioned_docs/version-29.0/ExpectAPI.md index f235097bda20..caba37d13841 100644 --- a/website/versioned_docs/version-29.0/ExpectAPI.md +++ b/website/versioned_docs/version-29.0/ExpectAPI.md @@ -281,7 +281,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.0/GlobalAPI.md b/website/versioned_docs/version-29.0/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.0/GlobalAPI.md +++ b/website/versioned_docs/version-29.0/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.0/JestObjectAPI.md b/website/versioned_docs/version-29.0/JestObjectAPI.md index 95648c18207a..277ec8a8e928 100644 --- a/website/versioned_docs/version-29.0/JestObjectAPI.md +++ b/website/versioned_docs/version-29.0/JestObjectAPI.md @@ -869,7 +869,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.0/JestPlatform.md b/website/versioned_docs/version-29.0/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.0/JestPlatform.md +++ b/website/versioned_docs/version-29.0/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.0/ManualMocks.md b/website/versioned_docs/version-29.0/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.0/ManualMocks.md +++ b/website/versioned_docs/version-29.0/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.0/MoreResources.md b/website/versioned_docs/version-29.0/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.0/MoreResources.md +++ b/website/versioned_docs/version-29.0/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.0/Puppeteer.md b/website/versioned_docs/version-29.0/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.0/Puppeteer.md +++ b/website/versioned_docs/version-29.0/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.0/SnapshotTesting.md b/website/versioned_docs/version-29.0/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.0/SnapshotTesting.md +++ b/website/versioned_docs/version-29.0/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.0/Troubleshooting.md b/website/versioned_docs/version-29.0/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.0/Troubleshooting.md +++ b/website/versioned_docs/version-29.0/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.0/TutorialAsync.md b/website/versioned_docs/version-29.0/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.0/TutorialAsync.md +++ b/website/versioned_docs/version-29.0/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.0/TutorialReact.md b/website/versioned_docs/version-29.0/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-29.0/TutorialReact.md +++ b/website/versioned_docs/version-29.0/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-29.0/TutorialReactNative.md b/website/versioned_docs/version-29.0/TutorialReactNative.md index c5a31d55a5bb..15b4537243f6 100644 --- a/website/versioned_docs/version-29.0/TutorialReactNative.md +++ b/website/versioned_docs/version-29.0/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.0/TutorialjQuery.md b/website/versioned_docs/version-29.0/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.0/TutorialjQuery.md +++ b/website/versioned_docs/version-29.0/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.0/UpgradingToJest29.md b/website/versioned_docs/version-29.0/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.0/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.0/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.0/WatchPlugins.md b/website/versioned_docs/version-29.0/WatchPlugins.md index fa48325d7255..652466a771c9 100644 --- a/website/versioned_docs/version-29.0/WatchPlugins.md +++ b/website/versioned_docs/version-29.0/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.0.3/packages/jest-types/src/Config.ts#L357-L419): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.1/CodeTransformation.md b/website/versioned_docs/version-29.1/CodeTransformation.md index f9c73b5420ee..7c3bafa48fde 100644 --- a/website/versioned_docs/version-29.1/CodeTransformation.md +++ b/website/versioned_docs/version-29.1/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.1/Configuration.md b/website/versioned_docs/version-29.1/Configuration.md index 1526b7c0de80..2124edfce7f1 100644 --- a/website/versioned_docs/version-29.1/Configuration.md +++ b/website/versioned_docs/version-29.1/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L421-L478). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L421-L478). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L421-L478). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L421-L478). :::info @@ -1330,7 +1330,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1512,7 +1512,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1760,7 +1760,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1783,9 +1783,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L421-L478) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L421-L478) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2072,7 +2072,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2112,7 +2112,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2154,7 +2154,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2369,7 +2369,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2387,7 +2387,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.1/ECMAScriptModules.md b/website/versioned_docs/version-29.1/ECMAScriptModules.md index 38e00b7ab514..75cbc17709ee 100644 --- a/website/versioned_docs/version-29.1/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.1/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -46,7 +46,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.1/ExpectAPI.md b/website/versioned_docs/version-29.1/ExpectAPI.md index f235097bda20..caba37d13841 100644 --- a/website/versioned_docs/version-29.1/ExpectAPI.md +++ b/website/versioned_docs/version-29.1/ExpectAPI.md @@ -281,7 +281,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.1/GlobalAPI.md b/website/versioned_docs/version-29.1/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.1/GlobalAPI.md +++ b/website/versioned_docs/version-29.1/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.1/JestObjectAPI.md b/website/versioned_docs/version-29.1/JestObjectAPI.md index 116b18bf74a4..e0fb7fd94676 100644 --- a/website/versioned_docs/version-29.1/JestObjectAPI.md +++ b/website/versioned_docs/version-29.1/JestObjectAPI.md @@ -946,7 +946,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.1/JestPlatform.md b/website/versioned_docs/version-29.1/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.1/JestPlatform.md +++ b/website/versioned_docs/version-29.1/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.1/ManualMocks.md b/website/versioned_docs/version-29.1/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.1/ManualMocks.md +++ b/website/versioned_docs/version-29.1/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.1/MoreResources.md b/website/versioned_docs/version-29.1/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.1/MoreResources.md +++ b/website/versioned_docs/version-29.1/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.1/Puppeteer.md b/website/versioned_docs/version-29.1/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.1/Puppeteer.md +++ b/website/versioned_docs/version-29.1/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.1/SnapshotTesting.md b/website/versioned_docs/version-29.1/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.1/SnapshotTesting.md +++ b/website/versioned_docs/version-29.1/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.1/Troubleshooting.md b/website/versioned_docs/version-29.1/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.1/Troubleshooting.md +++ b/website/versioned_docs/version-29.1/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.1/TutorialAsync.md b/website/versioned_docs/version-29.1/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.1/TutorialAsync.md +++ b/website/versioned_docs/version-29.1/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.1/TutorialReact.md b/website/versioned_docs/version-29.1/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-29.1/TutorialReact.md +++ b/website/versioned_docs/version-29.1/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-29.1/TutorialReactNative.md b/website/versioned_docs/version-29.1/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/website/versioned_docs/version-29.1/TutorialReactNative.md +++ b/website/versioned_docs/version-29.1/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.1/TutorialjQuery.md b/website/versioned_docs/version-29.1/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.1/TutorialjQuery.md +++ b/website/versioned_docs/version-29.1/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.1/UpgradingToJest29.md b/website/versioned_docs/version-29.1/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.1/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.1/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.1/WatchPlugins.md b/website/versioned_docs/version-29.1/WatchPlugins.md index 9790383217f3..add83cd17afb 100644 --- a/website/versioned_docs/version-29.1/WatchPlugins.md +++ b/website/versioned_docs/version-29.1/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.1.2/packages/jest-types/src/Config.ts#L357-L419): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.2/CodeTransformation.md b/website/versioned_docs/version-29.2/CodeTransformation.md index 608da10eb418..c961f2b1d823 100644 --- a/website/versioned_docs/version-29.2/CodeTransformation.md +++ b/website/versioned_docs/version-29.2/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.2/Configuration.md b/website/versioned_docs/version-29.2/Configuration.md index 552ca34a3e93..5d465a64f50a 100644 --- a/website/versioned_docs/version-29.2/Configuration.md +++ b/website/versioned_docs/version-29.2/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -1330,7 +1330,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1766,7 +1766,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1789,9 +1789,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2078,7 +2078,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2118,7 +2118,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2160,7 +2160,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2375,7 +2375,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2393,7 +2393,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.2/ECMAScriptModules.md b/website/versioned_docs/version-29.2/ECMAScriptModules.md index 38e00b7ab514..75cbc17709ee 100644 --- a/website/versioned_docs/version-29.2/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.2/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -46,7 +46,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.2/ExpectAPI.md b/website/versioned_docs/version-29.2/ExpectAPI.md index f235097bda20..caba37d13841 100644 --- a/website/versioned_docs/version-29.2/ExpectAPI.md +++ b/website/versioned_docs/version-29.2/ExpectAPI.md @@ -281,7 +281,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.2/GlobalAPI.md b/website/versioned_docs/version-29.2/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.2/GlobalAPI.md +++ b/website/versioned_docs/version-29.2/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.2/JestObjectAPI.md b/website/versioned_docs/version-29.2/JestObjectAPI.md index d5f1ef088641..aae2be24dfb5 100644 --- a/website/versioned_docs/version-29.2/JestObjectAPI.md +++ b/website/versioned_docs/version-29.2/JestObjectAPI.md @@ -956,7 +956,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.2/JestPlatform.md b/website/versioned_docs/version-29.2/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.2/JestPlatform.md +++ b/website/versioned_docs/version-29.2/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.2/ManualMocks.md b/website/versioned_docs/version-29.2/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.2/ManualMocks.md +++ b/website/versioned_docs/version-29.2/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.2/MoreResources.md b/website/versioned_docs/version-29.2/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.2/MoreResources.md +++ b/website/versioned_docs/version-29.2/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.2/Puppeteer.md b/website/versioned_docs/version-29.2/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.2/Puppeteer.md +++ b/website/versioned_docs/version-29.2/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.2/SnapshotTesting.md b/website/versioned_docs/version-29.2/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.2/SnapshotTesting.md +++ b/website/versioned_docs/version-29.2/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.2/Troubleshooting.md b/website/versioned_docs/version-29.2/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.2/Troubleshooting.md +++ b/website/versioned_docs/version-29.2/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.2/TutorialAsync.md b/website/versioned_docs/version-29.2/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.2/TutorialAsync.md +++ b/website/versioned_docs/version-29.2/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.2/TutorialReact.md b/website/versioned_docs/version-29.2/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-29.2/TutorialReact.md +++ b/website/versioned_docs/version-29.2/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-29.2/TutorialReactNative.md b/website/versioned_docs/version-29.2/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/website/versioned_docs/version-29.2/TutorialReactNative.md +++ b/website/versioned_docs/version-29.2/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.2/TutorialjQuery.md b/website/versioned_docs/version-29.2/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.2/TutorialjQuery.md +++ b/website/versioned_docs/version-29.2/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.2/UpgradingToJest29.md b/website/versioned_docs/version-29.2/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.2/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.2/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.2/WatchPlugins.md b/website/versioned_docs/version-29.2/WatchPlugins.md index acb66e0a8673..57ddeaec07e4 100644 --- a/website/versioned_docs/version-29.2/WatchPlugins.md +++ b/website/versioned_docs/version-29.2/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.3/CodeTransformation.md b/website/versioned_docs/version-29.3/CodeTransformation.md index 625b8d4fb27d..6e7f4cbeb969 100644 --- a/website/versioned_docs/version-29.3/CodeTransformation.md +++ b/website/versioned_docs/version-29.3/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.3/Configuration.md b/website/versioned_docs/version-29.3/Configuration.md index bdf7c836db4f..6afcbbb778c7 100644 --- a/website/versioned_docs/version-29.3/Configuration.md +++ b/website/versioned_docs/version-29.3/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -1330,7 +1330,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1512,7 +1512,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1766,7 +1766,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1789,9 +1789,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2078,7 +2078,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2118,7 +2118,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2160,7 +2160,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2375,7 +2375,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2393,7 +2393,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.3/ECMAScriptModules.md b/website/versioned_docs/version-29.3/ECMAScriptModules.md index 1aa9a39b0c68..feaed6bdb961 100644 --- a/website/versioned_docs/version-29.3/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.3/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -48,7 +48,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.3/ExpectAPI.md b/website/versioned_docs/version-29.3/ExpectAPI.md index f235097bda20..caba37d13841 100644 --- a/website/versioned_docs/version-29.3/ExpectAPI.md +++ b/website/versioned_docs/version-29.3/ExpectAPI.md @@ -281,7 +281,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.3/GlobalAPI.md b/website/versioned_docs/version-29.3/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.3/GlobalAPI.md +++ b/website/versioned_docs/version-29.3/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.3/JestObjectAPI.md b/website/versioned_docs/version-29.3/JestObjectAPI.md index 94d0f99115d9..472b7f1c3800 100644 --- a/website/versioned_docs/version-29.3/JestObjectAPI.md +++ b/website/versioned_docs/version-29.3/JestObjectAPI.md @@ -960,7 +960,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.3/JestPlatform.md b/website/versioned_docs/version-29.3/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.3/JestPlatform.md +++ b/website/versioned_docs/version-29.3/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.3/ManualMocks.md b/website/versioned_docs/version-29.3/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.3/ManualMocks.md +++ b/website/versioned_docs/version-29.3/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.3/MoreResources.md b/website/versioned_docs/version-29.3/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.3/MoreResources.md +++ b/website/versioned_docs/version-29.3/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.3/Puppeteer.md b/website/versioned_docs/version-29.3/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.3/Puppeteer.md +++ b/website/versioned_docs/version-29.3/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.3/SnapshotTesting.md b/website/versioned_docs/version-29.3/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.3/SnapshotTesting.md +++ b/website/versioned_docs/version-29.3/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.3/Troubleshooting.md b/website/versioned_docs/version-29.3/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.3/Troubleshooting.md +++ b/website/versioned_docs/version-29.3/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.3/TutorialAsync.md b/website/versioned_docs/version-29.3/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.3/TutorialAsync.md +++ b/website/versioned_docs/version-29.3/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.3/TutorialReact.md b/website/versioned_docs/version-29.3/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-29.3/TutorialReact.md +++ b/website/versioned_docs/version-29.3/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-29.3/TutorialReactNative.md b/website/versioned_docs/version-29.3/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/website/versioned_docs/version-29.3/TutorialReactNative.md +++ b/website/versioned_docs/version-29.3/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.3/TutorialjQuery.md b/website/versioned_docs/version-29.3/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.3/TutorialjQuery.md +++ b/website/versioned_docs/version-29.3/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.3/UpgradingToJest29.md b/website/versioned_docs/version-29.3/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.3/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.3/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.3/WatchPlugins.md b/website/versioned_docs/version-29.3/WatchPlugins.md index acb66e0a8673..57ddeaec07e4 100644 --- a/website/versioned_docs/version-29.3/WatchPlugins.md +++ b/website/versioned_docs/version-29.3/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.4/CodeTransformation.md b/website/versioned_docs/version-29.4/CodeTransformation.md index d2a568fcb024..14d96a16f649 100644 --- a/website/versioned_docs/version-29.4/CodeTransformation.md +++ b/website/versioned_docs/version-29.4/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.4/Configuration.md b/website/versioned_docs/version-29.4/Configuration.md index 6efbfb7fbc45..ed92e8e2bef9 100644 --- a/website/versioned_docs/version-29.4/Configuration.md +++ b/website/versioned_docs/version-29.4/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -1330,7 +1330,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1512,7 +1512,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1766,7 +1766,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1789,9 +1789,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2078,7 +2078,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2118,7 +2118,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2160,7 +2160,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2375,7 +2375,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2393,7 +2393,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.4/ECMAScriptModules.md b/website/versioned_docs/version-29.4/ECMAScriptModules.md index 1aa9a39b0c68..feaed6bdb961 100644 --- a/website/versioned_docs/version-29.4/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.4/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -48,7 +48,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.4/ExpectAPI.md b/website/versioned_docs/version-29.4/ExpectAPI.md index d140e0dd4340..46b2c361585e 100644 --- a/website/versioned_docs/version-29.4/ExpectAPI.md +++ b/website/versioned_docs/version-29.4/ExpectAPI.md @@ -1591,7 +1591,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.4/GlobalAPI.md b/website/versioned_docs/version-29.4/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.4/GlobalAPI.md +++ b/website/versioned_docs/version-29.4/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.4/JestObjectAPI.md b/website/versioned_docs/version-29.4/JestObjectAPI.md index a4619d66ca31..1a415aa24b87 100644 --- a/website/versioned_docs/version-29.4/JestObjectAPI.md +++ b/website/versioned_docs/version-29.4/JestObjectAPI.md @@ -1031,7 +1031,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.4/JestPlatform.md b/website/versioned_docs/version-29.4/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.4/JestPlatform.md +++ b/website/versioned_docs/version-29.4/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.4/ManualMocks.md b/website/versioned_docs/version-29.4/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.4/ManualMocks.md +++ b/website/versioned_docs/version-29.4/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.4/MoreResources.md b/website/versioned_docs/version-29.4/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.4/MoreResources.md +++ b/website/versioned_docs/version-29.4/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.4/Puppeteer.md b/website/versioned_docs/version-29.4/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.4/Puppeteer.md +++ b/website/versioned_docs/version-29.4/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.4/SnapshotTesting.md b/website/versioned_docs/version-29.4/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.4/SnapshotTesting.md +++ b/website/versioned_docs/version-29.4/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.4/Troubleshooting.md b/website/versioned_docs/version-29.4/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.4/Troubleshooting.md +++ b/website/versioned_docs/version-29.4/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.4/TutorialAsync.md b/website/versioned_docs/version-29.4/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.4/TutorialAsync.md +++ b/website/versioned_docs/version-29.4/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.4/TutorialReact.md b/website/versioned_docs/version-29.4/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-29.4/TutorialReact.md +++ b/website/versioned_docs/version-29.4/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-29.4/TutorialReactNative.md b/website/versioned_docs/version-29.4/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/website/versioned_docs/version-29.4/TutorialReactNative.md +++ b/website/versioned_docs/version-29.4/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.4/TutorialjQuery.md b/website/versioned_docs/version-29.4/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.4/TutorialjQuery.md +++ b/website/versioned_docs/version-29.4/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.4/UpgradingToJest29.md b/website/versioned_docs/version-29.4/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.4/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.4/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.4/WatchPlugins.md b/website/versioned_docs/version-29.4/WatchPlugins.md index acb66e0a8673..57ddeaec07e4 100644 --- a/website/versioned_docs/version-29.4/WatchPlugins.md +++ b/website/versioned_docs/version-29.4/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.5/CodeTransformation.md b/website/versioned_docs/version-29.5/CodeTransformation.md index d2a568fcb024..14d96a16f649 100644 --- a/website/versioned_docs/version-29.5/CodeTransformation.md +++ b/website/versioned_docs/version-29.5/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.5/Configuration.md b/website/versioned_docs/version-29.5/Configuration.md index b9ac0d926541..0604ca6f965a 100644 --- a/website/versioned_docs/version-29.5/Configuration.md +++ b/website/versioned_docs/version-29.5/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -1365,7 +1365,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1547,7 +1547,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1801,7 +1801,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1824,9 +1824,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2113,7 +2113,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2153,7 +2153,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2195,7 +2195,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2410,7 +2410,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2428,7 +2428,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.5/ECMAScriptModules.md b/website/versioned_docs/version-29.5/ECMAScriptModules.md index 1aa9a39b0c68..feaed6bdb961 100644 --- a/website/versioned_docs/version-29.5/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.5/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -48,7 +48,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.5/ExpectAPI.md b/website/versioned_docs/version-29.5/ExpectAPI.md index d140e0dd4340..46b2c361585e 100644 --- a/website/versioned_docs/version-29.5/ExpectAPI.md +++ b/website/versioned_docs/version-29.5/ExpectAPI.md @@ -1591,7 +1591,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.5/GlobalAPI.md b/website/versioned_docs/version-29.5/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.5/GlobalAPI.md +++ b/website/versioned_docs/version-29.5/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.5/JestObjectAPI.md b/website/versioned_docs/version-29.5/JestObjectAPI.md index d3811b628b86..130e6d7768a2 100644 --- a/website/versioned_docs/version-29.5/JestObjectAPI.md +++ b/website/versioned_docs/version-29.5/JestObjectAPI.md @@ -1071,7 +1071,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.5/JestPlatform.md b/website/versioned_docs/version-29.5/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.5/JestPlatform.md +++ b/website/versioned_docs/version-29.5/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.5/ManualMocks.md b/website/versioned_docs/version-29.5/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.5/ManualMocks.md +++ b/website/versioned_docs/version-29.5/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.5/MoreResources.md b/website/versioned_docs/version-29.5/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.5/MoreResources.md +++ b/website/versioned_docs/version-29.5/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.5/Puppeteer.md b/website/versioned_docs/version-29.5/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.5/Puppeteer.md +++ b/website/versioned_docs/version-29.5/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.5/SnapshotTesting.md b/website/versioned_docs/version-29.5/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.5/SnapshotTesting.md +++ b/website/versioned_docs/version-29.5/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.5/Troubleshooting.md b/website/versioned_docs/version-29.5/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.5/Troubleshooting.md +++ b/website/versioned_docs/version-29.5/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.5/TutorialAsync.md b/website/versioned_docs/version-29.5/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.5/TutorialAsync.md +++ b/website/versioned_docs/version-29.5/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.5/TutorialReact.md b/website/versioned_docs/version-29.5/TutorialReact.md index 673122b5facb..88bb4ebc6fef 100644 --- a/website/versioned_docs/version-29.5/TutorialReact.md +++ b/website/versioned_docs/version-29.5/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). #### Enzyme diff --git a/website/versioned_docs/version-29.5/TutorialReactNative.md b/website/versioned_docs/version-29.5/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/website/versioned_docs/version-29.5/TutorialReactNative.md +++ b/website/versioned_docs/version-29.5/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.5/TutorialjQuery.md b/website/versioned_docs/version-29.5/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.5/TutorialjQuery.md +++ b/website/versioned_docs/version-29.5/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.5/UpgradingToJest29.md b/website/versioned_docs/version-29.5/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.5/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.5/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.5/WatchPlugins.md b/website/versioned_docs/version-29.5/WatchPlugins.md index acb66e0a8673..57ddeaec07e4 100644 --- a/website/versioned_docs/version-29.5/WatchPlugins.md +++ b/website/versioned_docs/version-29.5/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript diff --git a/website/versioned_docs/version-29.6/CodeTransformation.md b/website/versioned_docs/version-29.6/CodeTransformation.md index d2a568fcb024..14d96a16f649 100644 --- a/website/versioned_docs/version-29.6/CodeTransformation.md +++ b/website/versioned_docs/version-29.6/CodeTransformation.md @@ -13,7 +13,7 @@ Jest will cache the result of a transformation and attempt to invalidate that re ## Defaults -Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest ships with one transformer out of the box – [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). It will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). :::tip @@ -134,7 +134,7 @@ type TransformerFactory = { :::note -The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/facebook/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). +The definitions above were trimmed down for brevity. Full code can be found in [Jest repo on GitHub](https://github.com/jestjs/jest/blob/main/packages/jest-transform/src/types.ts) (remember to choose the right tag/commit for your version of Jest). ::: diff --git a/website/versioned_docs/version-29.6/Configuration.md b/website/versioned_docs/version-29.6/Configuration.md index 0fe862f4bb3d..4e23e314b103 100644 --- a/website/versioned_docs/version-29.6/Configuration.md +++ b/website/versioned_docs/version-29.6/Configuration.md @@ -310,7 +310,7 @@ const config: Config = { export default config; ``` -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Config.ts). +For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). ### `coverageThreshold` \[object] @@ -772,7 +772,7 @@ If you specify a global reference value (like an object or array) here, and some Default: `undefined` -This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global setup module, which must export a function (it can be sync or async). The function will be triggered once before all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -807,7 +807,7 @@ module.exports = async function (globalConfig, projectConfig) { Default: `undefined` -This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). +This option allows the use of a custom global teardown module which must export a function (it can be sync or async). The function will be triggered once after all test suites and it will receive two arguments: Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481). :::info @@ -1401,7 +1401,7 @@ Hungry for reporters? Take a look at long list of [awesome reporters](https://gi ::: -Custom reporter module must export a class that takes [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/facebook/jest/blob/main/packages/jest-reporters/src/types.ts)): +Custom reporter module must export a class that takes [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422), `reporterOptions` and `reporterContext` as constructor arguments and implements at least `onRunComplete()` method (for the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts)): ```js title="custom-reporter.js" class CustomReporter { @@ -1583,7 +1583,7 @@ The `runner` property value can omit the `jest-runner-` prefix of the package na ::: -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) in the constructor, and has a `runTests` method with the signature: ```ts async function runTests( @@ -1837,7 +1837,7 @@ Pretty foo: Object { To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. -More about serializers API can be found [here](https://github.com/facebook/jest/tree/main/packages/pretty-format/README.md#serialize). +More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). ::: @@ -1860,9 +1860,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/facebook/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. The constructor is passed [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422) and [`projectConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L424-L481) as its first argument, and [`testEnvironmentContext`](https://github.com/jestjs/jest/blob/491e7cb0f2daa8263caccc72d48bdce7ba759b11/packages/jest-environment/src/index.ts#L13) as its second. -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. +The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. @@ -2149,7 +2149,7 @@ function testRunner( ): Promise; ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/main/packages/jest-jasmine2/src/index.ts). +An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). ### `testSequencer` \[string] @@ -2189,7 +2189,7 @@ class CustomSequencer extends Sequencer { */ sort(tests) { // Test structure information - // https://github.com/facebook/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 + // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 const copyTests = Array.from(tests); return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); } @@ -2231,7 +2231,7 @@ Default: `{"\\.[jt]sx?$": "babel-jest"}` A map from regular expressions to paths to transformers. Optionally, a tuple with configuration options can be passed as second argument: `{filePattern: ['path-to-transformer', {options}]}`. For example, here is how you can configure `babel-jest` for non-default behavior: `{'\\.js$': ['babel-jest', {rootMode: 'upward'}]}`. -Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/facebook/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). +Jest runs the code of your project as JavaScript, hence a transformer is needed if you use some syntax not supported by Node out of the box (such as JSX, TypeScript, Vue templates). By default, Jest will use [`babel-jest`](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup) transformer, which will load your project's Babel configuration and transform any file matching the `/\.[jt]sx?$/` RegExp (in other words, any `.js`, `.jsx`, `.ts` or `.tsx` file). In addition, `babel-jest` will inject the Babel plugin necessary for mock hoisting talked about in [ES Module mocking](ManualMocks.md#using-with-es-module-imports). See the [Code Transformation](CodeTransformation.md) section for more details and instructions on building your own transformer. @@ -2446,7 +2446,7 @@ Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawl Default: `undefined` -Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/facebook/jest/issues/11956); +Specifies the memory limit for workers before they are recycled and is primarily a work-around for [this issue](https://github.com/jestjs/jest/issues/11956); After the worker has executed a test the memory usage of it is checked. If it exceeds the value specified the worker is killed and restarted. The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: @@ -2464,7 +2464,7 @@ After the worker has executed a test the memory usage of it is checked. If it ex :::caution -Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/facebook/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. +Percentage based memory limit [does not work on Linux CircleCI workers](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) due to incorrect system memory being reported. ::: diff --git a/website/versioned_docs/version-29.6/ECMAScriptModules.md b/website/versioned_docs/version-29.6/ECMAScriptModules.md index 1aa9a39b0c68..feaed6bdb961 100644 --- a/website/versioned_docs/version-29.6/ECMAScriptModules.md +++ b/website/versioned_docs/version-29.6/ECMAScriptModules.md @@ -7,7 +7,7 @@ title: ECMAScript Modules Jest ships with **experimental** support for ECMAScript Modules (ESM). -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/facebook/jest/issues/9430) and the [label](https://github.com/facebook/jest/labels/ES%20Modules) on the issue tracker. +The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). @@ -48,7 +48,7 @@ import.meta.jest.useFakeTimers(); Since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work for ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. -ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/facebook/jest/issues/10025) for updates. +ESM mocking is supported through `jest.unstable_mockModule`. As the name suggests, this API is still work in progress, please follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. The usage of `jest.unstable_mockModule` is essentially the same as `jest.mock` with two differences: the factory function is required and it can be sync or async: diff --git a/website/versioned_docs/version-29.6/ExpectAPI.md b/website/versioned_docs/version-29.6/ExpectAPI.md index d140e0dd4340..46b2c361585e 100644 --- a/website/versioned_docs/version-29.6/ExpectAPI.md +++ b/website/versioned_docs/version-29.6/ExpectAPI.md @@ -1591,7 +1591,7 @@ A boolean to let you know this matcher was called with an `expand` option. When #### `this.utils` -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/facebook/jest/tree/main/packages/jest-matcher-utils). +There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: diff --git a/website/versioned_docs/version-29.6/GlobalAPI.md b/website/versioned_docs/version-29.6/GlobalAPI.md index 7a29a37a7ec1..c3a14d3c542c 100644 --- a/website/versioned_docs/version-29.6/GlobalAPI.md +++ b/website/versioned_docs/version-29.6/GlobalAPI.md @@ -505,7 +505,7 @@ Also under the alias: `it.concurrent(name, fn, timeout)` :::caution -`test.concurrent` is considered experimental - see [here](https://github.com/facebook/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. +`test.concurrent` is considered experimental - see [here](https://github.com/jestjs/jest/labels/Area%3A%20Concurrent) for details on missing features and other issues. ::: @@ -751,7 +751,7 @@ Also under the alias: `it.failing(name, fn, timeout)` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -783,7 +783,7 @@ Also under the alias: `it.failing.each(table)(name, fn)` and `` it.failing.each` :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -807,7 +807,7 @@ Also under the aliases: `it.only.failing(name, fn, timeout)`, `fit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: @@ -819,7 +819,7 @@ Also under the aliases: `it.skip.failing(name, fn, timeout)`, `xit.failing(name, :::note -This is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.6/JestObjectAPI.md b/website/versioned_docs/version-29.6/JestObjectAPI.md index d3811b628b86..130e6d7768a2 100644 --- a/website/versioned_docs/version-29.6/JestObjectAPI.md +++ b/website/versioned_docs/version-29.6/JestObjectAPI.md @@ -1071,7 +1071,7 @@ Returns the `jest` object for chaining. :::info -This function is only available with the default [jest-circus](https://github.com/facebook/jest/tree/main/packages/jest-circus) runner. +This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. ::: diff --git a/website/versioned_docs/version-29.6/JestPlatform.md b/website/versioned_docs/version-29.6/JestPlatform.md index 7e638e040b63..3e0ed9f07956 100644 --- a/website/versioned_docs/version-29.6/JestPlatform.md +++ b/website/versioned_docs/version-29.6/JestPlatform.md @@ -23,7 +23,7 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). ## jest-diff @@ -68,7 +68,7 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). ## jest-get-type @@ -115,7 +115,7 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). ## jest-worker @@ -147,7 +147,7 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/main/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). ## pretty-format @@ -167,4 +167,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/main/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-29.6/ManualMocks.md b/website/versioned_docs/version-29.6/ManualMocks.md index 48e5acdb21fc..d166114387eb 100644 --- a/website/versioned_docs/version-29.6/ManualMocks.md +++ b/website/versioned_docs/version-29.6/ManualMocks.md @@ -142,7 +142,7 @@ The example mock shown here uses [`jest.createMockFromModule`](JestObjectAPI.md# To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. -The code for this example is available at [examples/manual-mocks](https://github.com/facebook/jest/tree/main/examples/manual-mocks). +The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). ## Using with ES module imports diff --git a/website/versioned_docs/version-29.6/MoreResources.md b/website/versioned_docs/version-29.6/MoreResources.md index 32335ceacbf2..a53696153a7b 100644 --- a/website/versioned_docs/version-29.6/MoreResources.md +++ b/website/versioned_docs/version-29.6/MoreResources.md @@ -15,7 +15,7 @@ By now you should have a good idea of how Jest can help you test your applicatio ## Learn by example -You will find a number of example test cases in the [`examples`](https://github.com/facebook/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. +You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. ## Join the community diff --git a/website/versioned_docs/version-29.6/Puppeteer.md b/website/versioned_docs/version-29.6/Puppeteer.md index d437bda3743f..5f2a6ef2806c 100644 --- a/website/versioned_docs/version-29.6/Puppeteer.md +++ b/website/versioned_docs/version-29.6/Puppeteer.md @@ -7,7 +7,7 @@ With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async :::note -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/facebook/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. +Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. ::: diff --git a/website/versioned_docs/version-29.6/SnapshotTesting.md b/website/versioned_docs/version-29.6/SnapshotTesting.md index 2fcef23b1579..3a58dbc0a347 100644 --- a/website/versioned_docs/version-29.6/SnapshotTesting.md +++ b/website/versioned_docs/version-29.6/SnapshotTesting.md @@ -9,7 +9,7 @@ A typical snapshot test case renders a UI component, takes a snapshot, then comp ## Snapshot Testing with Jest -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/facebook/jest/blob/main/examples/snapshot/Link.js): +A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): ```tsx import renderer from 'react-test-renderer'; @@ -23,7 +23,7 @@ it('renders correctly', () => { }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: +The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -38,7 +38,7 @@ exports[`renders correctly 1`] = ` `; ``` -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/facebook/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. +The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. :::note @@ -84,7 +84,7 @@ Go ahead and accept the changes by running the above command. You may also use t If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. -You can try out this functionality by cloning the [snapshot example](https://github.com/facebook/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. ### Interactive Snapshot Mode @@ -252,7 +252,7 @@ The goal is to make it easy to review snapshots in pull requests, and fight agai Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a [Clock](https://github.com/facebook/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: +For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: ```js Date.now = jest.fn(() => 1482363367071); @@ -312,7 +312,7 @@ Yes, all snapshot files should be committed alongside the modules they are cover ### Does snapshot testing only work with React components? -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/facebook/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. ### What's the difference between snapshot testing and visual regression testing? diff --git a/website/versioned_docs/version-29.6/Troubleshooting.md b/website/versioned_docs/version-29.6/Troubleshooting.md index 42afe50c2f14..ffa30a558854 100644 --- a/website/versioned_docs/version-29.6/Troubleshooting.md +++ b/website/versioned_docs/version-29.6/Troubleshooting.md @@ -161,9 +161,9 @@ Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/tro ## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/facebook/jest/issues/1395) [discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). -Based on the [findings](https://github.com/facebook/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. +Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): diff --git a/website/versioned_docs/version-29.6/TutorialAsync.md b/website/versioned_docs/version-29.6/TutorialAsync.md index 80acc323a22e..4f9e4c4d5d24 100644 --- a/website/versioned_docs/version-29.6/TutorialAsync.md +++ b/website/versioned_docs/version-29.6/TutorialAsync.md @@ -156,6 +156,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/main/examples/async). +The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-29.6/TutorialReact.md b/website/versioned_docs/version-29.6/TutorialReact.md index 13165b1b4e95..fd6f7620acce 100644 --- a/website/versioned_docs/version-29.6/TutorialReact.md +++ b/website/versioned_docs/version-29.6/TutorialReact.md @@ -171,7 +171,7 @@ exports[`changes the class when hovered 3`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/main/examples/snapshot). +The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16+ @@ -259,7 +259,7 @@ it('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at [examples/react-testing-library](https://github.com/facebook/jest/tree/main/examples/react-testing-library). +The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). ### Custom transformers diff --git a/website/versioned_docs/version-29.6/TutorialReactNative.md b/website/versioned_docs/version-29.6/TutorialReactNative.md index b2b653078a85..4cd9a78a9a57 100644 --- a/website/versioned_docs/version-29.6/TutorialReactNative.md +++ b/website/versioned_docs/version-29.6/TutorialReactNative.md @@ -125,7 +125,7 @@ exports[`Intro renders correctly 1`] = ` The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. -The code for this example is available at [examples/react-native](https://github.com/facebook/jest/tree/main/examples/react-native). +The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). ## Preset configuration diff --git a/website/versioned_docs/version-29.6/TutorialjQuery.md b/website/versioned_docs/version-29.6/TutorialjQuery.md index 9f1be7caf513..a1c542a4f12b 100644 --- a/website/versioned_docs/version-29.6/TutorialjQuery.md +++ b/website/versioned_docs/version-29.6/TutorialjQuery.md @@ -69,4 +69,4 @@ To get started with the JSDOM [test environment](Configuration.md#testenvironmen npm install --save-dev jest-environment-jsdom ``` -The code for this example is available at [examples/jquery](https://github.com/facebook/jest/tree/main/examples/jquery). +The code for this example is available at [examples/jquery](https://github.com/jestjs/jest/tree/main/examples/jquery). diff --git a/website/versioned_docs/version-29.6/UpgradingToJest29.md b/website/versioned_docs/version-29.6/UpgradingToJest29.md index 49caf1de4736..842092f445c3 100644 --- a/website/versioned_docs/version-29.6/UpgradingToJest29.md +++ b/website/versioned_docs/version-29.6/UpgradingToJest29.md @@ -7,7 +7,7 @@ Upgrading Jest from v28 to v29? This guide aims to help refactoring your configu :::info -See [changelog](https://github.com/facebook/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. +See [changelog](https://github.com/jestjs/jest/blob/main/CHANGELOG.md#2900) for the full list of changes. ::: diff --git a/website/versioned_docs/version-29.6/WatchPlugins.md b/website/versioned_docs/version-29.6/WatchPlugins.md index acb66e0a8673..57ddeaec07e4 100644 --- a/website/versioned_docs/version-29.6/WatchPlugins.md +++ b/website/versioned_docs/version-29.6/WatchPlugins.md @@ -140,7 +140,7 @@ If the key for your plugin already exists as a default key, your plugin will ove To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. -- [`globalConfig`](https://github.com/facebook/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration +- [`globalConfig`](https://github.com/jestjs/jest/blob/v29.2.1/packages/jest-types/src/Config.ts#L358-L422): A representation of Jest's current global configuration - `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript From 0cbe04d42716928c2f67deac312d01b729b6021a Mon Sep 17 00:00:00 2001 From: Dmitri Date: Wed, 16 Aug 2023 09:05:30 +0300 Subject: [PATCH 003/101] fix(expect): remove @types/node from dependencies (#14385) --- CHANGELOG.md | 1 + packages/expect/package.json | 1 - packages/expect/src/types.ts | 3 +-- packages/jest-circus/src/run.ts | 4 +++- packages/jest-snapshot/src/index.ts | 2 +- yarn.lock | 1 - 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 79c5d914f531..ea832f3ebb3b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- `[expect]` Remove `@types/node` from dependencies ([#14385](https://github.com/jestjs/jest/pull/14385)) - `[jest-reporters]` Update `istanbul-lib-instrument` dependency to v6. ([#14401](https://github.com/jestjs/jest/pull/14401)) ### Chore & Maintenance diff --git a/packages/expect/package.json b/packages/expect/package.json index 8882f53f5002..9ec02caab9b1 100644 --- a/packages/expect/package.json +++ b/packages/expect/package.json @@ -20,7 +20,6 @@ }, "dependencies": { "@jest/expect-utils": "workspace:^", - "@types/node": "*", "jest-get-type": "workspace:^", "jest-matcher-utils": "workspace:^", "jest-message-util": "workspace:^", diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts index 96e858dad93d..e946ebd11e62 100644 --- a/packages/expect/src/types.ts +++ b/packages/expect/src/types.ts @@ -6,7 +6,6 @@ * */ -import type {AsyncLocalStorage} from 'async_hooks'; import type {EqualsFunction, Tester} from '@jest/expect-utils'; import type * as jestMatcherUtils from 'jest-matcher-utils'; import {INTERNAL_MATCHER_FLAG} from './jestMatchersObject'; @@ -58,7 +57,7 @@ export interface MatcherUtils { export interface MatcherState { assertionCalls: number; - currentConcurrentTestName?: AsyncLocalStorage; + currentConcurrentTestName?: () => string | undefined; currentTestName?: string; error?: Error; expand?: boolean; diff --git a/packages/jest-circus/src/run.ts b/packages/jest-circus/src/run.ts index 6564b92e8c45..02766579678f 100644 --- a/packages/jest-circus/src/run.ts +++ b/packages/jest-circus/src/run.ts @@ -137,7 +137,9 @@ function collectConcurrentTests( function startTestsConcurrently(concurrentTests: Array) { const mutex = pLimit(getState().maxConcurrency); const testNameStorage = new AsyncLocalStorage(); - jestExpect.setState({currentConcurrentTestName: testNameStorage}); + jestExpect.setState({ + currentConcurrentTestName: () => testNameStorage.getStore(), + }); for (const test of concurrentTests) { try { const testFn = test.fn; diff --git a/packages/jest-snapshot/src/index.ts b/packages/jest-snapshot/src/index.ts index ee15429a553a..a0344a7daccc 100644 --- a/packages/jest-snapshot/src/index.ts +++ b/packages/jest-snapshot/src/index.ts @@ -281,7 +281,7 @@ const _toMatchSnapshot = (config: MatchSnapshotConfig) => { const {currentConcurrentTestName, isNot, snapshotState} = context; const currentTestName = - currentConcurrentTestName?.getStore() ?? context.currentTestName; + currentConcurrentTestName?.() ?? context.currentTestName; if (isNot) { throw new Error( diff --git a/yarn.lock b/yarn.lock index 221e78957ae1..88827e52c5ae 100644 --- a/yarn.lock +++ b/yarn.lock @@ -9776,7 +9776,6 @@ __metadata: "@jest/expect-utils": "workspace:^" "@jest/test-utils": "workspace:^" "@tsd/typescript": ^5.0.4 - "@types/node": "*" chalk: ^4.0.0 immutable: ^4.0.0 jest-get-type: "workspace:^" From dde57f7b5fb5912a4c3182c93837ece29b270192 Mon Sep 17 00:00:00 2001 From: Vinicius Morais Dutra Date: Wed, 16 Aug 2023 03:20:53 -0300 Subject: [PATCH 004/101] docs: incorrect specification to the method jest.replaceProperty (#14388) --- docs/JestObjectAPI.md | 2 +- website/versioned_docs/version-29.4/JestObjectAPI.md | 2 +- website/versioned_docs/version-29.5/JestObjectAPI.md | 2 +- website/versioned_docs/version-29.6/JestObjectAPI.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 130e6d7768a2..16f20416fdc8 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -669,7 +669,7 @@ Creates a mock function similar to `jest.fn` but also tracks calls to `object[me :::note -By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `jest.replaceProperty(object, methodName, jest.fn(() => customImplementation));` +By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation)`. ::: diff --git a/website/versioned_docs/version-29.4/JestObjectAPI.md b/website/versioned_docs/version-29.4/JestObjectAPI.md index 1a415aa24b87..104d8332d377 100644 --- a/website/versioned_docs/version-29.4/JestObjectAPI.md +++ b/website/versioned_docs/version-29.4/JestObjectAPI.md @@ -669,7 +669,7 @@ Creates a mock function similar to `jest.fn` but also tracks calls to `object[me :::note -By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `jest.replaceProperty(object, methodName, jest.fn(() => customImplementation));` +By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation)`. ::: diff --git a/website/versioned_docs/version-29.5/JestObjectAPI.md b/website/versioned_docs/version-29.5/JestObjectAPI.md index 130e6d7768a2..16f20416fdc8 100644 --- a/website/versioned_docs/version-29.5/JestObjectAPI.md +++ b/website/versioned_docs/version-29.5/JestObjectAPI.md @@ -669,7 +669,7 @@ Creates a mock function similar to `jest.fn` but also tracks calls to `object[me :::note -By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `jest.replaceProperty(object, methodName, jest.fn(() => customImplementation));` +By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation)`. ::: diff --git a/website/versioned_docs/version-29.6/JestObjectAPI.md b/website/versioned_docs/version-29.6/JestObjectAPI.md index 130e6d7768a2..16f20416fdc8 100644 --- a/website/versioned_docs/version-29.6/JestObjectAPI.md +++ b/website/versioned_docs/version-29.6/JestObjectAPI.md @@ -669,7 +669,7 @@ Creates a mock function similar to `jest.fn` but also tracks calls to `object[me :::note -By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `jest.replaceProperty(object, methodName, jest.fn(() => customImplementation));` +By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation)`. ::: From a515a161baf652e8d9df84fa09c0571126bb155c Mon Sep 17 00:00:00 2001 From: Ben Kraft Date: Wed, 16 Aug 2023 06:15:02 -0700 Subject: [PATCH 005/101] fix(jest-core): don't use workers in watch mode if runInBand specified (#14085) --- CHANGELOG.md | 1 + packages/jest-config/src/index.ts | 1 + .../src/__tests__/testSchedulerHelper.test.js | 41 ++++++++++--------- .../logDebugMessages.test.ts.snap | 1 + packages/jest-core/src/testSchedulerHelper.ts | 7 ++-- packages/jest-types/src/Config.ts | 1 + packages/test-utils/src/config.ts | 1 + 7 files changed, 30 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea832f3ebb3b..e15bad622f72 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ### Fixes - `[expect]` Remove `@types/node` from dependencies ([#14385](https://github.com/jestjs/jest/pull/14385)) +- `[jest-core]` Use workers in watch mode by default to avoid crashes ([#14059](https://github.com/facebook/jest/pull/14059) & [#14085](https://github.com/facebook/jest/pull/14085)). - `[jest-reporters]` Update `istanbul-lib-instrument` dependency to v6. ([#14401](https://github.com/jestjs/jest/pull/14401)) ### Chore & Maintenance diff --git a/packages/jest-config/src/index.ts b/packages/jest-config/src/index.ts index ecdab9a89591..43093fd91f92 100644 --- a/packages/jest-config/src/index.ts +++ b/packages/jest-config/src/index.ts @@ -121,6 +121,7 @@ const groupOptions = ( replname: options.replname, reporters: options.reporters, rootDir: options.rootDir, + runInBand: options.runInBand, runTestsByPath: options.runTestsByPath, seed: options.seed, shard: options.shard, diff --git a/packages/jest-core/src/__tests__/testSchedulerHelper.test.js b/packages/jest-core/src/__tests__/testSchedulerHelper.test.js index d4fbc2756750..945add3f9497 100644 --- a/packages/jest-core/src/__tests__/testSchedulerHelper.test.js +++ b/packages/jest-core/src/__tests__/testSchedulerHelper.test.js @@ -23,25 +23,26 @@ const getTestMock = () => ({ const getTestsMock = () => [getTestMock(), getTestMock()]; test.each` - tests | timings | detectOpenHandles | maxWorkers | watch | workerIdleMemoryLimit | expectedResult - ${[getTestMock()]} | ${[500, 500]} | ${false} | ${undefined} | ${true} | ${undefined} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${false} | ${1} | ${true} | ${undefined} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${false} | ${2} | ${true} | ${undefined} | ${false} - ${[getTestMock()]} | ${[2000, 500]} | ${false} | ${undefined} | ${true} | ${undefined} | ${false} - ${getTestMock()} | ${[500, 500]} | ${false} | ${undefined} | ${true} | ${undefined} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${false} | ${1} | ${false} | ${undefined} | ${true} - ${getTestMock()} | ${[2000, 500]} | ${false} | ${2} | ${false} | ${undefined} | ${false} - ${[getTestMock()]} | ${[2000]} | ${false} | ${undefined} | ${false} | ${undefined} | ${true} - ${getTestsMock()} | ${[500, 500]} | ${false} | ${undefined} | ${false} | ${undefined} | ${true} - ${new Array(45)} | ${[500]} | ${false} | ${undefined} | ${false} | ${undefined} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${false} | ${undefined} | ${false} | ${undefined} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${true} | ${undefined} | ${false} | ${undefined} | ${true} - ${[getTestMock()]} | ${[500, 500]} | ${false} | ${undefined} | ${true} | ${'500MB'} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${false} | ${1} | ${true} | ${'500MB'} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${false} | ${1} | ${false} | ${'500MB'} | ${false} - ${[getTestMock()]} | ${[2000]} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false} - ${getTestsMock()} | ${[500, 500]} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false} - ${getTestsMock()} | ${[2000, 500]} | ${true} | ${undefined} | ${false} | ${'500MB'} | ${true} + tests | timings | detectOpenHandles | runInBand | maxWorkers | watch | workerIdleMemoryLimit | expectedResult + ${[getTestMock()]} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${true} | ${undefined} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${2} | ${true} | ${undefined} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${true} | ${1} | ${true} | ${undefined} | ${true} + ${[getTestMock()]} | ${[2000, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false} + ${getTestMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${undefined} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${false} | ${undefined} | ${true} + ${getTestMock()} | ${[2000, 500]} | ${false} | ${false} | ${2} | ${false} | ${undefined} | ${false} + ${[getTestMock()]} | ${[2000]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${true} + ${getTestsMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${true} + ${new Array(45)} | ${[500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${undefined} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${true} | ${false} | ${undefined} | ${false} | ${undefined} | ${true} + ${[getTestMock()]} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${true} | ${'500MB'} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${true} | ${'500MB'} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${false} | ${false} | ${1} | ${false} | ${'500MB'} | ${false} + ${[getTestMock()]} | ${[2000]} | ${false} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false} + ${getTestsMock()} | ${[500, 500]} | ${false} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${false} + ${getTestsMock()} | ${[2000, 500]} | ${true} | ${false} | ${undefined} | ${false} | ${'500MB'} | ${true} `( 'shouldRunInBand() - should return $expectedResult for runInBand mode', ({ @@ -49,6 +50,7 @@ test.each` timings, detectOpenHandles, maxWorkers, + runInBand, watch, workerIdleMemoryLimit, expectedResult, @@ -57,6 +59,7 @@ test.each` shouldRunInBand(tests, timings, { detectOpenHandles, maxWorkers, + runInBand, watch, workerIdleMemoryLimit, }), diff --git a/packages/jest-core/src/lib/__tests__/__snapshots__/logDebugMessages.test.ts.snap b/packages/jest-core/src/lib/__tests__/__snapshots__/logDebugMessages.test.ts.snap index 7e9a1b8f96fc..1f288c9a76d1 100644 --- a/packages/jest-core/src/lib/__tests__/__snapshots__/logDebugMessages.test.ts.snap +++ b/packages/jest-core/src/lib/__tests__/__snapshots__/logDebugMessages.test.ts.snap @@ -101,6 +101,7 @@ exports[`prints the config object 1`] = ` "projects": [], "reporters": [], "rootDir": "/test_root_dir/", + "runInBand": false, "runTestsByPath": false, "seed": 1234, "silent": false, diff --git a/packages/jest-core/src/testSchedulerHelper.ts b/packages/jest-core/src/testSchedulerHelper.ts index 79c7a056ee95..121025f3746c 100644 --- a/packages/jest-core/src/testSchedulerHelper.ts +++ b/packages/jest-core/src/testSchedulerHelper.ts @@ -16,13 +16,15 @@ export function shouldRunInBand( { detectOpenHandles, maxWorkers, + runInBand, watch, watchAll, workerIdleMemoryLimit, }: Config.GlobalConfig, ): boolean { + // If user asked for run in band, respect that. // detectOpenHandles makes no sense without runInBand, because it cannot detect leaks in workers - if (detectOpenHandles) { + if (runInBand || detectOpenHandles) { return true; } @@ -39,9 +41,6 @@ export function shouldRunInBand( * Otherwise, run in band if we only have one test or one worker available. * Also, if we are confident from previous runs that the tests will finish * quickly we also run in band to reduce the overhead of spawning workers. - * Finally, the user can provide the runInBand argument in the CLI to - * force running in band, which sets maxWorkers to 1 here: - * https://github.com/jestjs/jest/blob/d106643a8ee0ffa9c2f11c6bb2d12094e99135aa/packages/jest-config/src/getMaxWorkers.ts#L27-L28 */ const areFastTests = timings.every(timing => timing < SLOW_TEST_TIME); const oneWorkerOrLess = maxWorkers <= 1; diff --git a/packages/jest-types/src/Config.ts b/packages/jest-types/src/Config.ts index 024896fb8a0b..307dee61f30a 100644 --- a/packages/jest-types/src/Config.ts +++ b/packages/jest-types/src/Config.ts @@ -400,6 +400,7 @@ export type GlobalConfig = { randomize?: boolean; replname?: string; reporters?: Array; + runInBand: boolean; runTestsByPath: boolean; rootDir: string; seed: number; diff --git a/packages/test-utils/src/config.ts b/packages/test-utils/src/config.ts index 61b6ded274b2..b427dcc9e3fb 100644 --- a/packages/test-utils/src/config.ts +++ b/packages/test-utils/src/config.ts @@ -47,6 +47,7 @@ const DEFAULT_GLOBAL_CONFIG: Config.GlobalConfig = { replname: undefined, reporters: [], rootDir: '/test_root_dir/', + runInBand: false, runTestsByPath: false, seed: 1234, silent: false, From a5cdc8652f4d8206e0ec91edb603437bf76e2048 Mon Sep 17 00:00:00 2001 From: "renovate[bot]" <29139614+renovate[bot]@users.noreply.github.com> Date: Wed, 16 Aug 2023 15:24:42 +0200 Subject: [PATCH 006/101] fix(deps): update dependency clsx to v2 (#14364) Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> --- website/package.json | 2 +- yarn.lock | 11 +++++++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/website/package.json b/website/package.json index cb45586b1f89..463c27060d9e 100644 --- a/website/package.json +++ b/website/package.json @@ -37,7 +37,7 @@ "@docusaurus/plugin-pwa": "^2.0.0", "@docusaurus/preset-classic": "^2.0.0", "@docusaurus/remark-plugin-npm2yarn": "^2.0.0", - "clsx": "^1.1.1", + "clsx": "^2.0.0", "docusaurus-remark-plugin-tab-blocks": "^1.2.0", "react": "^17.0.2", "react-dom": "^17.0.2", diff --git a/yarn.lock b/yarn.lock index 88827e52c5ae..68ff4925f6ec 100644 --- a/yarn.lock +++ b/yarn.lock @@ -7399,13 +7399,20 @@ __metadata: languageName: node linkType: hard -"clsx@npm:^1.1.1, clsx@npm:^1.2.1": +"clsx@npm:^1.2.1": version: 1.2.1 resolution: "clsx@npm:1.2.1" checksum: 30befca8019b2eb7dbad38cff6266cf543091dae2825c856a62a8ccf2c3ab9c2907c4d12b288b73101196767f66812365400a227581484a05f968b0307cfaf12 languageName: node linkType: hard +"clsx@npm:^2.0.0": + version: 2.0.0 + resolution: "clsx@npm:2.0.0" + checksum: a2cfb2351b254611acf92faa0daf15220f4cd648bdf96ce369d729813b85336993871a4bf6978ddea2b81b5a130478339c20d9d0b5c6fc287e5147f0c059276e + languageName: node + linkType: hard + "cmd-shim@npm:^6.0.0": version: 6.0.1 resolution: "cmd-shim@npm:6.0.1" @@ -12982,7 +12989,7 @@ __metadata: "@docusaurus/remark-plugin-npm2yarn": ^2.0.0 "@tsconfig/docusaurus": ^1.0.5 "@types/react": ^17.0.3 - clsx: ^1.1.1 + clsx: ^2.0.0 docusaurus-remark-plugin-tab-blocks: ^1.2.0 graphql: ^16.3.0 graphql-request: ^6.0.0 From 9c8fdbbe1fa1d58faf9d0293be16bf61f548bb15 Mon Sep 17 00:00:00 2001 From: cin Date: Thu, 17 Aug 2023 17:51:01 +0800 Subject: [PATCH 007/101] fix: symbol key could not be enum (#14414) --- CHANGELOG.md | 1 + packages/expect-utils/src/utils.ts | 2 +- .../src/__tests__/asymmetricMatchers.test.ts | 8 +++++++ packages/expect/src/asymmetricMatchers.ts | 24 +++++++++++-------- 4 files changed, 24 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e15bad622f72..2bbc4accd8ca 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### Fixes +- `[expect, @jest/expect-utils]` `ObjectContaining` support `sumbol` as key ([#14414](https://github.com/jestjs/jest/pull/14414)) - `[expect]` Remove `@types/node` from dependencies ([#14385](https://github.com/jestjs/jest/pull/14385)) - `[jest-core]` Use workers in watch mode by default to avoid crashes ([#14059](https://github.com/facebook/jest/pull/14059) & [#14085](https://github.com/facebook/jest/pull/14085)). - `[jest-reporters]` Update `istanbul-lib-instrument` dependency to v6. ([#14401](https://github.com/jestjs/jest/pull/14401)) diff --git a/packages/expect-utils/src/utils.ts b/packages/expect-utils/src/utils.ts index cb4ab7fda33f..ed5c2e36bf74 100644 --- a/packages/expect-utils/src/utils.ts +++ b/packages/expect-utils/src/utils.ts @@ -47,7 +47,7 @@ const hasPropertyInObject = (object: object, key: string | symbol): boolean => { // the prototype chain for string keys but not for symbols. (Otherwise, it // could find values such as a Set or Map's Symbol.toStringTag, with unexpected // results.) -const getObjectKeys = (object: object) => [ +export const getObjectKeys = (object: object): Array => [ ...Object.keys(object), ...Object.getOwnPropertySymbols(object), ]; diff --git a/packages/expect/src/__tests__/asymmetricMatchers.test.ts b/packages/expect/src/__tests__/asymmetricMatchers.test.ts index 24a326e21899..3fb5f90835ef 100644 --- a/packages/expect/src/__tests__/asymmetricMatchers.test.ts +++ b/packages/expect/src/__tests__/asymmetricMatchers.test.ts @@ -181,6 +181,7 @@ test('ArrayNotContaining throws for non-arrays', () => { }); test('ObjectContaining matches', () => { + const foo = Symbol('foo'); [ objectContaining({}).asymmetricMatch('jest'), objectContaining({foo: 'foo'}).asymmetricMatch({foo: 'foo', jest: 'jest'}), @@ -192,12 +193,15 @@ test('ObjectContaining matches', () => { foo: Buffer.from('foo'), jest: 'jest', }), + objectContaining({[foo]: 'foo'}).asymmetricMatch({[foo]: 'foo'}), ].forEach(test => { jestExpect(test).toEqual(true); }); }); test('ObjectContaining does not match', () => { + const foo = Symbol('foo'); + const bar = Symbol('bar'); [ objectContaining({foo: 'foo'}).asymmetricMatch({bar: 'bar'}), objectContaining({foo: 'foo'}).asymmetricMatch({foo: 'foox'}), @@ -206,6 +210,7 @@ test('ObjectContaining does not match', () => { answer: 42, foo: {bar: 'baz', foobar: 'qux'}, }).asymmetricMatch({foo: {bar: 'baz'}}), + objectContaining({[foo]: 'foo'}).asymmetricMatch({[bar]: 'bar'}), ].forEach(test => { jestExpect(test).toEqual(false); }); @@ -250,9 +255,12 @@ test('ObjectContaining does not mutate the sample', () => { }); test('ObjectNotContaining matches', () => { + const foo = Symbol('foo'); + const bar = Symbol('bar'); [ objectContaining({}).asymmetricMatch(null), objectContaining({}).asymmetricMatch(undefined), + objectNotContaining({[foo]: 'foo'}).asymmetricMatch({[bar]: 'bar'}), objectNotContaining({foo: 'foo'}).asymmetricMatch({bar: 'bar'}), objectNotContaining({foo: 'foo'}).asymmetricMatch({foo: 'foox'}), objectNotContaining({foo: undefined}).asymmetricMatch({}), diff --git a/packages/expect/src/asymmetricMatchers.ts b/packages/expect/src/asymmetricMatchers.ts index 1eb9c52fa66d..5bd543ac5297 100644 --- a/packages/expect/src/asymmetricMatchers.ts +++ b/packages/expect/src/asymmetricMatchers.ts @@ -8,6 +8,7 @@ import { equals, + getObjectKeys, isA, iterableEquality, subsetEquality, @@ -52,7 +53,10 @@ function getPrototype(obj: object) { return obj.constructor.prototype; } -export function hasProperty(obj: object | null, property: string): boolean { +export function hasProperty( + obj: object | null, + property: string | symbol, +): boolean { if (!obj) { return false; } @@ -216,8 +220,10 @@ class ArrayContaining extends AsymmetricMatcher> { } } -class ObjectContaining extends AsymmetricMatcher> { - constructor(sample: Record, inverse = false) { +class ObjectContaining extends AsymmetricMatcher< + Record +> { + constructor(sample: Record, inverse = false) { super(sample, inverse); } @@ -232,14 +238,12 @@ class ObjectContaining extends AsymmetricMatcher> { let result = true; const matcherContext = this.getMatcherContext(); - for (const property in this.sample) { + const objectKeys = getObjectKeys(this.sample); + + for (const key of objectKeys) { if ( - !hasProperty(other, property) || - !equals( - this.sample[property], - other[property], - matcherContext.customTesters, - ) + !hasProperty(other, key) || + !equals(this.sample[key], other[key], matcherContext.customTesters) ) { result = false; break; From eb6170227ef13381d9dd24ca42508ef50c2a278c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?S=C3=A9bastien=20Lorber?= Date: Fri, 18 Aug 2023 09:19:18 +0200 Subject: [PATCH 008/101] Archive docs versions 29.3 and below (#14425) --- package.json | 2 +- website/archivedVersions.json | 8 + website/docusaurus.config.js | 2 +- website/src/pages/versions.js | 3 +- .../version-25.x/Architecture.md | 16 - .../version-25.x/BypassingModuleMocks.md | 58 - website/versioned_docs/version-25.x/CLI.md | 438 --- .../version-25.x/Configuration.md | 1447 ---------- .../versioned_docs/version-25.x/DynamoDB.md | 81 - .../version-25.x/ECMAScriptModules.md | 75 - .../version-25.x/EnvironmentVariables.md | 14 - .../version-25.x/Es6ClassMocks.md | 448 --- .../versioned_docs/version-25.x/ExpectAPI.md | 1451 ---------- .../version-25.x/GettingStarted.md | 175 -- .../versioned_docs/version-25.x/GlobalAPI.md | 678 ----- .../version-25.x/JestCommunity.md | 21 - .../version-25.x/JestObjectAPI.md | 724 ----- .../version-25.x/JestPlatform.md | 170 -- .../version-25.x/ManualMocks.md | 188 -- .../version-25.x/MigrationGuide.md | 22 - .../version-25.x/MockFunctionAPI.md | 487 ---- .../version-25.x/MockFunctions.md | 320 --- .../versioned_docs/version-25.x/MongoDB.md | 61 - .../version-25.x/MoreResources.md | 24 - .../versioned_docs/version-25.x/Puppeteer.md | 175 -- .../version-25.x/SetupAndTeardown.md | 190 -- .../version-25.x/SnapshotTesting.md | 332 --- .../version-25.x/TestingAsyncCode.md | 144 - .../version-25.x/TestingFrameworks.md | 49 - .../versioned_docs/version-25.x/TimerMocks.md | 185 -- .../version-25.x/Troubleshooting.md | 209 -- .../version-25.x/TutorialAsync.md | 161 -- .../version-25.x/TutorialReact.md | 313 --- .../version-25.x/TutorialReactNative.md | 219 -- .../version-25.x/TutorialjQuery.md | 66 - .../version-25.x/UsingMatchers.md | 178 -- .../version-25.x/WatchPlugins.md | 244 -- .../versioned_docs/version-25.x/Webpack.md | 241 -- .../version-26.x/Architecture.md | 16 - .../version-26.x/BypassingModuleMocks.md | 58 - website/versioned_docs/version-26.x/CLI.md | 458 ---- .../version-26.x/Configuration.md | 1543 ----------- .../versioned_docs/version-26.x/DynamoDB.md | 81 - .../version-26.x/ECMAScriptModules.md | 75 - .../version-26.x/EnvironmentVariables.md | 14 - .../version-26.x/Es6ClassMocks.md | 448 --- .../versioned_docs/version-26.x/ExpectAPI.md | 1451 ---------- .../version-26.x/GettingStarted.md | 175 -- .../versioned_docs/version-26.x/GlobalAPI.md | 850 ------ .../version-26.x/JestCommunity.md | 21 - .../version-26.x/JestObjectAPI.md | 758 ----- .../version-26.x/JestPlatform.md | 170 -- .../version-26.x/ManualMocks.md | 188 -- .../version-26.x/MigrationGuide.md | 22 - .../version-26.x/MockFunctionAPI.md | 487 ---- .../version-26.x/MockFunctions.md | 320 --- .../versioned_docs/version-26.x/MongoDB.md | 61 - .../version-26.x/MoreResources.md | 24 - .../versioned_docs/version-26.x/Puppeteer.md | 175 -- .../version-26.x/SetupAndTeardown.md | 190 -- .../version-26.x/SnapshotTesting.md | 332 --- .../version-26.x/TestingAsyncCode.md | 144 - .../version-26.x/TestingFrameworks.md | 49 - .../versioned_docs/version-26.x/TimerMocks.md | 169 -- .../version-26.x/Troubleshooting.md | 209 -- .../version-26.x/TutorialAsync.md | 161 -- .../version-26.x/TutorialReact.md | 313 --- .../version-26.x/TutorialReactNative.md | 219 -- .../version-26.x/TutorialjQuery.md | 66 - .../version-26.x/UsingMatchers.md | 178 -- .../version-26.x/WatchPlugins.md | 244 -- .../versioned_docs/version-26.x/Webpack.md | 241 -- .../version-27.x/Architecture.md | 16 - .../version-27.x/BypassingModuleMocks.md | 58 - website/versioned_docs/version-27.x/CLI.md | 462 ---- .../version-27.x/CodeTransformation.md | 176 -- .../version-27.x/Configuration.md | 1616 ----------- .../versioned_docs/version-27.x/DynamoDB.md | 81 - .../version-27.x/ECMAScriptModules.md | 95 - .../version-27.x/EnvironmentVariables.md | 14 - .../version-27.x/Es6ClassMocks.md | 448 --- .../versioned_docs/version-27.x/ExpectAPI.md | 1485 ---------- .../version-27.x/GettingStarted.md | 173 -- .../versioned_docs/version-27.x/GlobalAPI.md | 888 ------ .../version-27.x/JestCommunity.md | 21 - .../version-27.x/JestObjectAPI.md | 804 ------ .../version-27.x/JestPlatform.md | 170 -- .../version-27.x/ManualMocks.md | 188 -- .../version-27.x/MigrationGuide.md | 22 - .../version-27.x/MockFunctionAPI.md | 497 ---- .../version-27.x/MockFunctions.md | 323 --- .../versioned_docs/version-27.x/MongoDB.md | 61 - .../version-27.x/MoreResources.md | 24 - .../versioned_docs/version-27.x/Puppeteer.md | 175 -- .../version-27.x/SetupAndTeardown.md | 238 -- .../version-27.x/SnapshotTesting.md | 324 --- .../version-27.x/TestingAsyncCode.md | 144 - .../version-27.x/TestingFrameworks.md | 49 - .../versioned_docs/version-27.x/TimerMocks.md | 185 -- .../version-27.x/Troubleshooting.md | 209 -- .../version-27.x/TutorialAsync.md | 161 -- .../version-27.x/TutorialReact.md | 315 --- .../version-27.x/TutorialReactNative.md | 219 -- .../version-27.x/TutorialjQuery.md | 66 - .../version-27.x/UsingMatchers.md | 178 -- .../version-27.x/WatchPlugins.md | 244 -- .../versioned_docs/version-27.x/Webpack.md | 241 -- .../version-28.x/Architecture.md | 16 - .../version-28.x/BypassingModuleMocks.md | 58 - website/versioned_docs/version-28.x/CLI.md | 480 ---- .../version-28.x/CodeTransformation.md | 196 -- .../version-28.x/Configuration.md | 1782 ------------ .../versioned_docs/version-28.x/DynamoDB.md | 81 - .../version-28.x/ECMAScriptModules.md | 100 - .../version-28.x/EnvironmentVariables.md | 14 - .../version-28.x/Es6ClassMocks.md | 448 --- .../versioned_docs/version-28.x/ExpectAPI.md | 1485 ---------- .../version-28.x/GettingStarted.md | 175 -- .../versioned_docs/version-28.x/GlobalAPI.md | 944 ------- .../version-28.x/JestCommunity.md | 21 - .../version-28.x/JestObjectAPI.md | 914 ------- .../version-28.x/JestPlatform.md | 170 -- .../version-28.x/ManualMocks.md | 188 -- .../version-28.x/MigrationGuide.md | 22 - .../version-28.x/MockFunctionAPI.md | 560 ---- .../version-28.x/MockFunctions.md | 328 --- .../versioned_docs/version-28.x/MongoDB.md | 61 - .../version-28.x/MoreResources.md | 24 - .../versioned_docs/version-28.x/Puppeteer.md | 175 -- .../version-28.x/SetupAndTeardown.md | 238 -- .../version-28.x/SnapshotTesting.md | 339 --- .../version-28.x/TestingAsyncCode.md | 144 - .../version-28.x/TestingFrameworks.md | 49 - .../versioned_docs/version-28.x/TimerMocks.md | 187 -- .../version-28.x/Troubleshooting.md | 221 -- .../version-28.x/TutorialAsync.md | 161 -- .../version-28.x/TutorialReact.md | 329 --- .../version-28.x/TutorialReactNative.md | 219 -- .../version-28.x/TutorialjQuery.md | 72 - .../version-28.x/UpgradingToJest28.md | 216 -- .../version-28.x/UsingMatchers.md | 178 -- .../version-28.x/WatchPlugins.md | 244 -- .../versioned_docs/version-28.x/Webpack.md | 241 -- .../version-28.x/_TypeScriptExamplesNote.md | 9 - .../version-29.0/Architecture.md | 16 - .../version-29.0/BypassingModuleMocks.md | 58 - website/versioned_docs/version-29.0/CLI.md | 474 ---- .../version-29.0/CodeTransformation.md | 196 -- .../version-29.0/Configuration.md | 2425 ---------------- .../versioned_docs/version-29.0/DynamoDB.md | 81 - .../version-29.0/ECMAScriptModules.md | 100 - .../version-29.0/EnvironmentVariables.md | 14 - .../version-29.0/Es6ClassMocks.md | 448 --- .../versioned_docs/version-29.0/ExpectAPI.md | 1584 ----------- .../version-29.0/GettingStarted.md | 202 -- .../versioned_docs/version-29.0/GlobalAPI.md | 1081 -------- .../version-29.0/JestCommunity.md | 21 - .../version-29.0/JestObjectAPI.md | 892 ------ .../version-29.0/JestPlatform.md | 170 -- .../version-29.0/ManualMocks.md | 188 -- .../version-29.0/MigrationGuide.md | 22 - .../version-29.0/MockFunctionAPI.md | 632 ----- .../version-29.0/MockFunctions.md | 328 --- .../versioned_docs/version-29.0/MongoDB.md | 61 - .../version-29.0/MoreResources.md | 24 - .../versioned_docs/version-29.0/Puppeteer.md | 175 -- .../version-29.0/SetupAndTeardown.md | 238 -- .../version-29.0/SnapshotTesting.md | 339 --- .../version-29.0/TestingAsyncCode.md | 144 - .../version-29.0/TestingFrameworks.md | 49 - .../versioned_docs/version-29.0/TimerMocks.md | 187 -- .../version-29.0/Troubleshooting.md | 221 -- .../version-29.0/TutorialAsync.md | 161 -- .../version-29.0/TutorialReact.md | 329 --- .../version-29.0/TutorialReactNative.md | 219 -- .../version-29.0/TutorialjQuery.md | 72 - .../version-29.0/UpgradingToJest29.md | 77 - .../version-29.0/UsingMatchers.md | 178 -- .../version-29.0/WatchPlugins.md | 244 -- .../versioned_docs/version-29.0/Webpack.md | 241 -- .../version-29.0/_TypeScriptExamplesNote.md | 11 - .../version-29.1/Architecture.md | 16 - .../version-29.1/BypassingModuleMocks.md | 58 - website/versioned_docs/version-29.1/CLI.md | 474 ---- .../version-29.1/CodeTransformation.md | 196 -- .../version-29.1/Configuration.md | 2425 ---------------- .../versioned_docs/version-29.1/DynamoDB.md | 81 - .../version-29.1/ECMAScriptModules.md | 100 - .../version-29.1/EnvironmentVariables.md | 14 - .../version-29.1/Es6ClassMocks.md | 448 --- .../versioned_docs/version-29.1/ExpectAPI.md | 1584 ----------- .../version-29.1/GettingStarted.md | 206 -- .../versioned_docs/version-29.1/GlobalAPI.md | 1081 -------- .../version-29.1/JestCommunity.md | 21 - .../version-29.1/JestObjectAPI.md | 969 ------- .../version-29.1/JestPlatform.md | 170 -- .../version-29.1/ManualMocks.md | 188 -- .../version-29.1/MigrationGuide.md | 22 - .../version-29.1/MockFunctionAPI.md | 685 ----- .../version-29.1/MockFunctions.md | 328 --- .../versioned_docs/version-29.1/MongoDB.md | 61 - .../version-29.1/MoreResources.md | 24 - .../versioned_docs/version-29.1/Puppeteer.md | 175 -- .../version-29.1/SetupAndTeardown.md | 238 -- .../version-29.1/SnapshotTesting.md | 339 --- .../version-29.1/TestingAsyncCode.md | 144 - .../version-29.1/TestingFrameworks.md | 49 - .../versioned_docs/version-29.1/TimerMocks.md | 187 -- .../version-29.1/Troubleshooting.md | 221 -- .../version-29.1/TutorialAsync.md | 161 -- .../version-29.1/TutorialReact.md | 329 --- .../version-29.1/TutorialReactNative.md | 219 -- .../version-29.1/TutorialjQuery.md | 72 - .../version-29.1/UpgradingToJest29.md | 77 - .../version-29.1/UsingMatchers.md | 178 -- .../version-29.1/WatchPlugins.md | 244 -- .../versioned_docs/version-29.1/Webpack.md | 241 -- .../version-29.1/_TypeScriptExamplesNote.md | 11 - .../version-29.2/Architecture.md | 16 - .../version-29.2/BypassingModuleMocks.md | 58 - website/versioned_docs/version-29.2/CLI.md | 494 ---- .../version-29.2/CodeTransformation.md | 196 -- .../version-29.2/Configuration.md | 2431 ----------------- .../versioned_docs/version-29.2/DynamoDB.md | 81 - .../version-29.2/ECMAScriptModules.md | 100 - .../version-29.2/EnvironmentVariables.md | 14 - .../version-29.2/Es6ClassMocks.md | 448 --- .../versioned_docs/version-29.2/ExpectAPI.md | 1584 ----------- .../version-29.2/GettingStarted.md | 206 -- .../versioned_docs/version-29.2/GlobalAPI.md | 1081 -------- .../version-29.2/JestCommunity.md | 21 - .../version-29.2/JestObjectAPI.md | 979 ------- .../version-29.2/JestPlatform.md | 170 -- .../version-29.2/ManualMocks.md | 188 -- .../version-29.2/MigrationGuide.md | 22 - .../version-29.2/MockFunctionAPI.md | 685 ----- .../version-29.2/MockFunctions.md | 328 --- .../versioned_docs/version-29.2/MongoDB.md | 61 - .../version-29.2/MoreResources.md | 24 - .../versioned_docs/version-29.2/Puppeteer.md | 175 -- .../version-29.2/SetupAndTeardown.md | 238 -- .../version-29.2/SnapshotTesting.md | 339 --- .../version-29.2/TestingAsyncCode.md | 144 - .../version-29.2/TestingFrameworks.md | 49 - .../versioned_docs/version-29.2/TimerMocks.md | 187 -- .../version-29.2/Troubleshooting.md | 221 -- .../version-29.2/TutorialAsync.md | 161 -- .../version-29.2/TutorialReact.md | 329 --- .../version-29.2/TutorialReactNative.md | 219 -- .../version-29.2/TutorialjQuery.md | 72 - .../version-29.2/UpgradingToJest29.md | 77 - .../version-29.2/UsingMatchers.md | 178 -- .../version-29.2/WatchPlugins.md | 244 -- .../versioned_docs/version-29.2/Webpack.md | 241 -- .../version-29.2/_TypeScriptExamplesNote.md | 11 - .../version-29.3/Architecture.md | 16 - .../version-29.3/BypassingModuleMocks.md | 58 - website/versioned_docs/version-29.3/CLI.md | 494 ---- .../version-29.3/CodeTransformation.md | 196 -- .../version-29.3/Configuration.md | 2431 ----------------- .../versioned_docs/version-29.3/DynamoDB.md | 81 - .../version-29.3/ECMAScriptModules.md | 102 - .../version-29.3/EnvironmentVariables.md | 14 - .../version-29.3/Es6ClassMocks.md | 448 --- .../versioned_docs/version-29.3/ExpectAPI.md | 1584 ----------- .../version-29.3/GettingStarted.md | 206 -- .../versioned_docs/version-29.3/GlobalAPI.md | 1081 -------- .../version-29.3/JestCommunity.md | 21 - .../version-29.3/JestObjectAPI.md | 983 ------- .../version-29.3/JestPlatform.md | 170 -- .../version-29.3/ManualMocks.md | 188 -- .../version-29.3/MigrationGuide.md | 22 - .../version-29.3/MockFunctionAPI.md | 719 ----- .../version-29.3/MockFunctions.md | 328 --- .../versioned_docs/version-29.3/MongoDB.md | 61 - .../version-29.3/MoreResources.md | 24 - .../versioned_docs/version-29.3/Puppeteer.md | 175 -- .../version-29.3/SetupAndTeardown.md | 238 -- .../version-29.3/SnapshotTesting.md | 339 --- .../version-29.3/TestingAsyncCode.md | 144 - .../version-29.3/TestingFrameworks.md | 49 - .../versioned_docs/version-29.3/TimerMocks.md | 187 -- .../version-29.3/Troubleshooting.md | 221 -- .../version-29.3/TutorialAsync.md | 161 -- .../version-29.3/TutorialReact.md | 329 --- .../version-29.3/TutorialReactNative.md | 219 -- .../version-29.3/TutorialjQuery.md | 72 - .../version-29.3/UpgradingToJest29.md | 77 - .../version-29.3/UsingMatchers.md | 178 -- .../version-29.3/WatchPlugins.md | 244 -- .../versioned_docs/version-29.3/Webpack.md | 242 -- .../version-29.3/_TypeScriptExamplesNote.md | 11 - .../version-25.x-sidebars.json | 160 -- .../version-26.x-sidebars.json | 160 -- .../version-27.x-sidebars.json | 47 - .../version-28.x-sidebars.json | 50 - .../version-29.0-sidebars.json | 50 - .../version-29.1-sidebars.json | 50 - .../version-29.2-sidebars.json | 50 - .../version-29.3-sidebars.json | 50 - website/versions.json | 10 +- 301 files changed, 13 insertions(+), 89725 deletions(-) delete mode 100644 website/versioned_docs/version-25.x/Architecture.md delete mode 100644 website/versioned_docs/version-25.x/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-25.x/CLI.md delete mode 100644 website/versioned_docs/version-25.x/Configuration.md delete mode 100644 website/versioned_docs/version-25.x/DynamoDB.md delete mode 100644 website/versioned_docs/version-25.x/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-25.x/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-25.x/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-25.x/ExpectAPI.md delete mode 100644 website/versioned_docs/version-25.x/GettingStarted.md delete mode 100644 website/versioned_docs/version-25.x/GlobalAPI.md delete mode 100644 website/versioned_docs/version-25.x/JestCommunity.md delete mode 100644 website/versioned_docs/version-25.x/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-25.x/JestPlatform.md delete mode 100644 website/versioned_docs/version-25.x/ManualMocks.md delete mode 100644 website/versioned_docs/version-25.x/MigrationGuide.md delete mode 100644 website/versioned_docs/version-25.x/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-25.x/MockFunctions.md delete mode 100644 website/versioned_docs/version-25.x/MongoDB.md delete mode 100644 website/versioned_docs/version-25.x/MoreResources.md delete mode 100644 website/versioned_docs/version-25.x/Puppeteer.md delete mode 100644 website/versioned_docs/version-25.x/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-25.x/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-25.x/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-25.x/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-25.x/TimerMocks.md delete mode 100644 website/versioned_docs/version-25.x/Troubleshooting.md delete mode 100644 website/versioned_docs/version-25.x/TutorialAsync.md delete mode 100644 website/versioned_docs/version-25.x/TutorialReact.md delete mode 100644 website/versioned_docs/version-25.x/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-25.x/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-25.x/UsingMatchers.md delete mode 100644 website/versioned_docs/version-25.x/WatchPlugins.md delete mode 100644 website/versioned_docs/version-25.x/Webpack.md delete mode 100644 website/versioned_docs/version-26.x/Architecture.md delete mode 100644 website/versioned_docs/version-26.x/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-26.x/CLI.md delete mode 100644 website/versioned_docs/version-26.x/Configuration.md delete mode 100644 website/versioned_docs/version-26.x/DynamoDB.md delete mode 100644 website/versioned_docs/version-26.x/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-26.x/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-26.x/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-26.x/ExpectAPI.md delete mode 100644 website/versioned_docs/version-26.x/GettingStarted.md delete mode 100644 website/versioned_docs/version-26.x/GlobalAPI.md delete mode 100644 website/versioned_docs/version-26.x/JestCommunity.md delete mode 100644 website/versioned_docs/version-26.x/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-26.x/JestPlatform.md delete mode 100644 website/versioned_docs/version-26.x/ManualMocks.md delete mode 100644 website/versioned_docs/version-26.x/MigrationGuide.md delete mode 100644 website/versioned_docs/version-26.x/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-26.x/MockFunctions.md delete mode 100644 website/versioned_docs/version-26.x/MongoDB.md delete mode 100644 website/versioned_docs/version-26.x/MoreResources.md delete mode 100644 website/versioned_docs/version-26.x/Puppeteer.md delete mode 100644 website/versioned_docs/version-26.x/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-26.x/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-26.x/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-26.x/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-26.x/TimerMocks.md delete mode 100644 website/versioned_docs/version-26.x/Troubleshooting.md delete mode 100644 website/versioned_docs/version-26.x/TutorialAsync.md delete mode 100644 website/versioned_docs/version-26.x/TutorialReact.md delete mode 100644 website/versioned_docs/version-26.x/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-26.x/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-26.x/UsingMatchers.md delete mode 100644 website/versioned_docs/version-26.x/WatchPlugins.md delete mode 100644 website/versioned_docs/version-26.x/Webpack.md delete mode 100644 website/versioned_docs/version-27.x/Architecture.md delete mode 100644 website/versioned_docs/version-27.x/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-27.x/CLI.md delete mode 100644 website/versioned_docs/version-27.x/CodeTransformation.md delete mode 100644 website/versioned_docs/version-27.x/Configuration.md delete mode 100644 website/versioned_docs/version-27.x/DynamoDB.md delete mode 100644 website/versioned_docs/version-27.x/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-27.x/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-27.x/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-27.x/ExpectAPI.md delete mode 100644 website/versioned_docs/version-27.x/GettingStarted.md delete mode 100644 website/versioned_docs/version-27.x/GlobalAPI.md delete mode 100644 website/versioned_docs/version-27.x/JestCommunity.md delete mode 100644 website/versioned_docs/version-27.x/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-27.x/JestPlatform.md delete mode 100644 website/versioned_docs/version-27.x/ManualMocks.md delete mode 100644 website/versioned_docs/version-27.x/MigrationGuide.md delete mode 100644 website/versioned_docs/version-27.x/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-27.x/MockFunctions.md delete mode 100644 website/versioned_docs/version-27.x/MongoDB.md delete mode 100644 website/versioned_docs/version-27.x/MoreResources.md delete mode 100644 website/versioned_docs/version-27.x/Puppeteer.md delete mode 100644 website/versioned_docs/version-27.x/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-27.x/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-27.x/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-27.x/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-27.x/TimerMocks.md delete mode 100644 website/versioned_docs/version-27.x/Troubleshooting.md delete mode 100644 website/versioned_docs/version-27.x/TutorialAsync.md delete mode 100644 website/versioned_docs/version-27.x/TutorialReact.md delete mode 100644 website/versioned_docs/version-27.x/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-27.x/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-27.x/UsingMatchers.md delete mode 100644 website/versioned_docs/version-27.x/WatchPlugins.md delete mode 100644 website/versioned_docs/version-27.x/Webpack.md delete mode 100644 website/versioned_docs/version-28.x/Architecture.md delete mode 100644 website/versioned_docs/version-28.x/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-28.x/CLI.md delete mode 100644 website/versioned_docs/version-28.x/CodeTransformation.md delete mode 100644 website/versioned_docs/version-28.x/Configuration.md delete mode 100644 website/versioned_docs/version-28.x/DynamoDB.md delete mode 100644 website/versioned_docs/version-28.x/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-28.x/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-28.x/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-28.x/ExpectAPI.md delete mode 100644 website/versioned_docs/version-28.x/GettingStarted.md delete mode 100644 website/versioned_docs/version-28.x/GlobalAPI.md delete mode 100644 website/versioned_docs/version-28.x/JestCommunity.md delete mode 100644 website/versioned_docs/version-28.x/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-28.x/JestPlatform.md delete mode 100644 website/versioned_docs/version-28.x/ManualMocks.md delete mode 100644 website/versioned_docs/version-28.x/MigrationGuide.md delete mode 100644 website/versioned_docs/version-28.x/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-28.x/MockFunctions.md delete mode 100644 website/versioned_docs/version-28.x/MongoDB.md delete mode 100644 website/versioned_docs/version-28.x/MoreResources.md delete mode 100644 website/versioned_docs/version-28.x/Puppeteer.md delete mode 100644 website/versioned_docs/version-28.x/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-28.x/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-28.x/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-28.x/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-28.x/TimerMocks.md delete mode 100644 website/versioned_docs/version-28.x/Troubleshooting.md delete mode 100644 website/versioned_docs/version-28.x/TutorialAsync.md delete mode 100644 website/versioned_docs/version-28.x/TutorialReact.md delete mode 100644 website/versioned_docs/version-28.x/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-28.x/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-28.x/UpgradingToJest28.md delete mode 100644 website/versioned_docs/version-28.x/UsingMatchers.md delete mode 100644 website/versioned_docs/version-28.x/WatchPlugins.md delete mode 100644 website/versioned_docs/version-28.x/Webpack.md delete mode 100644 website/versioned_docs/version-28.x/_TypeScriptExamplesNote.md delete mode 100644 website/versioned_docs/version-29.0/Architecture.md delete mode 100644 website/versioned_docs/version-29.0/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-29.0/CLI.md delete mode 100644 website/versioned_docs/version-29.0/CodeTransformation.md delete mode 100644 website/versioned_docs/version-29.0/Configuration.md delete mode 100644 website/versioned_docs/version-29.0/DynamoDB.md delete mode 100644 website/versioned_docs/version-29.0/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-29.0/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-29.0/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-29.0/ExpectAPI.md delete mode 100644 website/versioned_docs/version-29.0/GettingStarted.md delete mode 100644 website/versioned_docs/version-29.0/GlobalAPI.md delete mode 100644 website/versioned_docs/version-29.0/JestCommunity.md delete mode 100644 website/versioned_docs/version-29.0/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-29.0/JestPlatform.md delete mode 100644 website/versioned_docs/version-29.0/ManualMocks.md delete mode 100644 website/versioned_docs/version-29.0/MigrationGuide.md delete mode 100644 website/versioned_docs/version-29.0/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-29.0/MockFunctions.md delete mode 100644 website/versioned_docs/version-29.0/MongoDB.md delete mode 100644 website/versioned_docs/version-29.0/MoreResources.md delete mode 100644 website/versioned_docs/version-29.0/Puppeteer.md delete mode 100644 website/versioned_docs/version-29.0/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-29.0/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-29.0/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-29.0/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-29.0/TimerMocks.md delete mode 100644 website/versioned_docs/version-29.0/Troubleshooting.md delete mode 100644 website/versioned_docs/version-29.0/TutorialAsync.md delete mode 100644 website/versioned_docs/version-29.0/TutorialReact.md delete mode 100644 website/versioned_docs/version-29.0/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-29.0/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-29.0/UpgradingToJest29.md delete mode 100644 website/versioned_docs/version-29.0/UsingMatchers.md delete mode 100644 website/versioned_docs/version-29.0/WatchPlugins.md delete mode 100644 website/versioned_docs/version-29.0/Webpack.md delete mode 100644 website/versioned_docs/version-29.0/_TypeScriptExamplesNote.md delete mode 100644 website/versioned_docs/version-29.1/Architecture.md delete mode 100644 website/versioned_docs/version-29.1/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-29.1/CLI.md delete mode 100644 website/versioned_docs/version-29.1/CodeTransformation.md delete mode 100644 website/versioned_docs/version-29.1/Configuration.md delete mode 100644 website/versioned_docs/version-29.1/DynamoDB.md delete mode 100644 website/versioned_docs/version-29.1/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-29.1/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-29.1/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-29.1/ExpectAPI.md delete mode 100644 website/versioned_docs/version-29.1/GettingStarted.md delete mode 100644 website/versioned_docs/version-29.1/GlobalAPI.md delete mode 100644 website/versioned_docs/version-29.1/JestCommunity.md delete mode 100644 website/versioned_docs/version-29.1/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-29.1/JestPlatform.md delete mode 100644 website/versioned_docs/version-29.1/ManualMocks.md delete mode 100644 website/versioned_docs/version-29.1/MigrationGuide.md delete mode 100644 website/versioned_docs/version-29.1/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-29.1/MockFunctions.md delete mode 100644 website/versioned_docs/version-29.1/MongoDB.md delete mode 100644 website/versioned_docs/version-29.1/MoreResources.md delete mode 100644 website/versioned_docs/version-29.1/Puppeteer.md delete mode 100644 website/versioned_docs/version-29.1/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-29.1/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-29.1/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-29.1/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-29.1/TimerMocks.md delete mode 100644 website/versioned_docs/version-29.1/Troubleshooting.md delete mode 100644 website/versioned_docs/version-29.1/TutorialAsync.md delete mode 100644 website/versioned_docs/version-29.1/TutorialReact.md delete mode 100644 website/versioned_docs/version-29.1/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-29.1/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-29.1/UpgradingToJest29.md delete mode 100644 website/versioned_docs/version-29.1/UsingMatchers.md delete mode 100644 website/versioned_docs/version-29.1/WatchPlugins.md delete mode 100644 website/versioned_docs/version-29.1/Webpack.md delete mode 100644 website/versioned_docs/version-29.1/_TypeScriptExamplesNote.md delete mode 100644 website/versioned_docs/version-29.2/Architecture.md delete mode 100644 website/versioned_docs/version-29.2/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-29.2/CLI.md delete mode 100644 website/versioned_docs/version-29.2/CodeTransformation.md delete mode 100644 website/versioned_docs/version-29.2/Configuration.md delete mode 100644 website/versioned_docs/version-29.2/DynamoDB.md delete mode 100644 website/versioned_docs/version-29.2/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-29.2/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-29.2/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-29.2/ExpectAPI.md delete mode 100644 website/versioned_docs/version-29.2/GettingStarted.md delete mode 100644 website/versioned_docs/version-29.2/GlobalAPI.md delete mode 100644 website/versioned_docs/version-29.2/JestCommunity.md delete mode 100644 website/versioned_docs/version-29.2/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-29.2/JestPlatform.md delete mode 100644 website/versioned_docs/version-29.2/ManualMocks.md delete mode 100644 website/versioned_docs/version-29.2/MigrationGuide.md delete mode 100644 website/versioned_docs/version-29.2/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-29.2/MockFunctions.md delete mode 100644 website/versioned_docs/version-29.2/MongoDB.md delete mode 100644 website/versioned_docs/version-29.2/MoreResources.md delete mode 100644 website/versioned_docs/version-29.2/Puppeteer.md delete mode 100644 website/versioned_docs/version-29.2/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-29.2/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-29.2/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-29.2/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-29.2/TimerMocks.md delete mode 100644 website/versioned_docs/version-29.2/Troubleshooting.md delete mode 100644 website/versioned_docs/version-29.2/TutorialAsync.md delete mode 100644 website/versioned_docs/version-29.2/TutorialReact.md delete mode 100644 website/versioned_docs/version-29.2/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-29.2/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-29.2/UpgradingToJest29.md delete mode 100644 website/versioned_docs/version-29.2/UsingMatchers.md delete mode 100644 website/versioned_docs/version-29.2/WatchPlugins.md delete mode 100644 website/versioned_docs/version-29.2/Webpack.md delete mode 100644 website/versioned_docs/version-29.2/_TypeScriptExamplesNote.md delete mode 100644 website/versioned_docs/version-29.3/Architecture.md delete mode 100644 website/versioned_docs/version-29.3/BypassingModuleMocks.md delete mode 100644 website/versioned_docs/version-29.3/CLI.md delete mode 100644 website/versioned_docs/version-29.3/CodeTransformation.md delete mode 100644 website/versioned_docs/version-29.3/Configuration.md delete mode 100644 website/versioned_docs/version-29.3/DynamoDB.md delete mode 100644 website/versioned_docs/version-29.3/ECMAScriptModules.md delete mode 100644 website/versioned_docs/version-29.3/EnvironmentVariables.md delete mode 100644 website/versioned_docs/version-29.3/Es6ClassMocks.md delete mode 100644 website/versioned_docs/version-29.3/ExpectAPI.md delete mode 100644 website/versioned_docs/version-29.3/GettingStarted.md delete mode 100644 website/versioned_docs/version-29.3/GlobalAPI.md delete mode 100644 website/versioned_docs/version-29.3/JestCommunity.md delete mode 100644 website/versioned_docs/version-29.3/JestObjectAPI.md delete mode 100644 website/versioned_docs/version-29.3/JestPlatform.md delete mode 100644 website/versioned_docs/version-29.3/ManualMocks.md delete mode 100644 website/versioned_docs/version-29.3/MigrationGuide.md delete mode 100644 website/versioned_docs/version-29.3/MockFunctionAPI.md delete mode 100644 website/versioned_docs/version-29.3/MockFunctions.md delete mode 100644 website/versioned_docs/version-29.3/MongoDB.md delete mode 100644 website/versioned_docs/version-29.3/MoreResources.md delete mode 100644 website/versioned_docs/version-29.3/Puppeteer.md delete mode 100644 website/versioned_docs/version-29.3/SetupAndTeardown.md delete mode 100644 website/versioned_docs/version-29.3/SnapshotTesting.md delete mode 100644 website/versioned_docs/version-29.3/TestingAsyncCode.md delete mode 100644 website/versioned_docs/version-29.3/TestingFrameworks.md delete mode 100644 website/versioned_docs/version-29.3/TimerMocks.md delete mode 100644 website/versioned_docs/version-29.3/Troubleshooting.md delete mode 100644 website/versioned_docs/version-29.3/TutorialAsync.md delete mode 100644 website/versioned_docs/version-29.3/TutorialReact.md delete mode 100644 website/versioned_docs/version-29.3/TutorialReactNative.md delete mode 100644 website/versioned_docs/version-29.3/TutorialjQuery.md delete mode 100644 website/versioned_docs/version-29.3/UpgradingToJest29.md delete mode 100644 website/versioned_docs/version-29.3/UsingMatchers.md delete mode 100644 website/versioned_docs/version-29.3/WatchPlugins.md delete mode 100644 website/versioned_docs/version-29.3/Webpack.md delete mode 100644 website/versioned_docs/version-29.3/_TypeScriptExamplesNote.md delete mode 100644 website/versioned_sidebars/version-25.x-sidebars.json delete mode 100644 website/versioned_sidebars/version-26.x-sidebars.json delete mode 100644 website/versioned_sidebars/version-27.x-sidebars.json delete mode 100644 website/versioned_sidebars/version-28.x-sidebars.json delete mode 100644 website/versioned_sidebars/version-29.0-sidebars.json delete mode 100644 website/versioned_sidebars/version-29.1-sidebars.json delete mode 100644 website/versioned_sidebars/version-29.2-sidebars.json delete mode 100644 website/versioned_sidebars/version-29.3-sidebars.json diff --git a/package.json b/package.json index 5634746093aa..6e7271f5ace3 100644 --- a/package.json +++ b/package.json @@ -92,7 +92,7 @@ "clean-all": "yarn clean-e2e && yarn build-clean && rimraf --glob './packages/*/node_modules' && rimraf './node_modules'", "clean-e2e": "node ./scripts/cleanE2e.mjs", "crowdin:upload": "echo 'Uploading sources to Crowdin' && crowdin upload sources --config ./crowdin.yaml", - "crowdin:download": "echo 'Downloading translations from Crowdin' && crowdin download --config ./crowdin.yaml", + "crowdin:download": "echo 'Downloading translations from Crowdin' && crowdin download --config ./crowdin.yaml --language ja --language es-ES --language fr --language pt-BR --language ro --language ru --language uk --language zh-CN", "jest": "node ./packages/jest-cli/bin/jest.js", "jest-jasmine": "JEST_JASMINE=1 yarn jest", "jest-jasmine-ci": "yarn jest-jasmine --color --config jest.config.ci.mjs", diff --git a/website/archivedVersions.json b/website/archivedVersions.json index f35f2e15d9f4..c6b91cd516a4 100644 --- a/website/archivedVersions.json +++ b/website/archivedVersions.json @@ -1,4 +1,12 @@ { + "29.3": "https://jest-archive-august-2023.netlify.app/docs/29.3/getting-started/", + "29.2": "https://jest-archive-august-2023.netlify.app/docs/29.2/getting-started/", + "29.1": "https://jest-archive-august-2023.netlify.app/docs/29.1/getting-started/", + "29.0": "https://jest-archive-august-2023.netlify.app/docs/29.0/getting-started/", + "28.x": "https://jest-archive-august-2023.netlify.app/docs/28.x/getting-started/", + "27.x": "https://jest-archive-august-2023.netlify.app/docs/27.x/getting-started/", + "26.x": "https://jest-archive-august-2023.netlify.app/docs/26.x/getting-started/", + "25.x": "https://jest-archive-august-2023.netlify.app/docs/25.x/getting-started/", "24.x": "https://archive.jestjs.io/docs/en/24.x/getting-started.html", "23.x": "https://archive.jestjs.io/docs/en/23.x/getting-started.html", "22.x": "https://archive.jestjs.io/docs/en/22.x/getting-started.html" diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js index 14649b3574de..a2c419c25713 100644 --- a/website/docusaurus.config.js +++ b/website/docusaurus.config.js @@ -183,7 +183,7 @@ const config = { dropdownItemsAfter: [ ...Object.entries(ArchivedVersions).map( ([versionName, versionUrl]) => ({ - to: versionUrl, + href: versionUrl, label: versionName, }) ), diff --git a/website/src/pages/versions.js b/website/src/pages/versions.js index 60c28373af81..3967551ccf0c 100644 --- a/website/src/pages/versions.js +++ b/website/src/pages/versions.js @@ -83,7 +83,8 @@ export default function VersionsPage() {

Archived Versions

- Here you can find documentation for archived versions of Jest. + Here you can find archived documentation for older versions of + Jest.

diff --git a/website/versioned_docs/version-25.x/Architecture.md b/website/versioned_docs/version-25.x/Architecture.md deleted file mode 100644 index 8d9a7c1d5eba..000000000000 --- a/website/versioned_docs/version-25.x/Architecture.md +++ /dev/null @@ -1,16 +0,0 @@ ---- -id: architecture -title: Architecture ---- - -import LiteYouTubeEmbed from 'react-lite-youtube-embed'; - -If you are interested in learning more about how Jest works, understand its architecture, and how Jest is split up into individual reusable packages, check out this video: - - - -If you'd like to learn how to build a testing framework like Jest from scratch, check out this video: - - - -There is also a [written guide you can follow](https://cpojer.net/posts/building-a-javascript-testing-framework). It teaches the fundamental concepts of Jest and explains how various parts of Jest can be used to compose a custom testing framework. diff --git a/website/versioned_docs/version-25.x/BypassingModuleMocks.md b/website/versioned_docs/version-25.x/BypassingModuleMocks.md deleted file mode 100644 index ba3ed65d95d4..000000000000 --- a/website/versioned_docs/version-25.x/BypassingModuleMocks.md +++ /dev/null @@ -1,58 +0,0 @@ ---- -id: bypassing-module-mocks -title: Bypassing module mocks ---- - -Jest allows you to mock out whole modules in your tests, which can be useful for testing if your code is calling functions from that module correctly. However, sometimes you may want to use parts of a mocked module in your _test file_, in which case you want to access the original implementation, rather than a mocked version. - -Consider writing a test case for this `createUser` function: - -```javascript title="createUser.js" -import fetch from 'node-fetch'; - -export const createUser = async () => { - const response = await fetch('https://website.com/users', {method: 'POST'}); - const userId = await response.text(); - return userId; -}; -``` - -Your test will want to mock the `fetch` function so that we can be sure that it gets called without actually making the network request. However, you'll also need to mock the return value of `fetch` with a `Response` (wrapped in a `Promise`), as our function uses it to grab the created user's ID. So you might initially try writing a test like this: - -```javascript -jest.mock('node-fetch'); - -import fetch, {Response} from 'node-fetch'; -import {createUser} from './createUser'; - -test('createUser calls fetch with the right args and returns the user id', async () => { - fetch.mockReturnValue(Promise.resolve(new Response('4'))); - - const userId = await createUser(); - - expect(fetch).toHaveBeenCalledTimes(1); - expect(fetch).toHaveBeenCalledWith('https://website.com/users', { - method: 'POST', - }); - expect(userId).toBe('4'); -}); -``` - -However, if you ran that test you would find that the `createUser` function would fail, throwing the error: `TypeError: response.text is not a function`. This is because the `Response` class you've imported from `node-fetch` has been mocked (due to the `jest.mock` call at the top of the test file) so it no longer behaves the way it should. - -To get around problems like this, Jest provides the `jest.requireActual` helper. To make the above test work, make the following change to the imports in the test file: - -```javascript -// BEFORE -jest.mock('node-fetch'); -import fetch, {Response} from 'node-fetch'; -``` - -```javascript -// AFTER -jest.mock('node-fetch'); -import fetch from 'node-fetch'; -const {Response} = jest.requireActual('node-fetch'); -``` - -This allows your test file to import the actual `Response` object from `node-fetch`, rather than a mocked version. This means the test will now pass correctly. diff --git a/website/versioned_docs/version-25.x/CLI.md b/website/versioned_docs/version-25.x/CLI.md deleted file mode 100644 index 3b0809b7aec1..000000000000 --- a/website/versioned_docs/version-25.x/CLI.md +++ /dev/null @@ -1,438 +0,0 @@ ---- -id: cli -title: Jest CLI Options ---- - -The `jest` command line runner has a number of useful options. You can run `jest --help` to view all available options. Many of the options shown below can also be used together to run tests exactly the way you want. Every one of Jest's [Configuration](Configuration.md) options can also be specified through the CLI. - -Here is a brief overview: - -## Running from the command line - -Run all tests (default): - -```bash -jest -``` - -Run only the tests that were specified with a pattern or filename: - -```bash -jest my-test #or -jest path/to/my-test.js -``` - -Run tests related to changed files based on hg/git (uncommitted files): - -```bash -jest -o -``` - -Run tests related to `path/to/fileA.js` and `path/to/fileB.js`: - -```bash -jest --findRelatedTests path/to/fileA.js path/to/fileB.js -``` - -Run tests that match this spec name (match against the name in `describe` or `test`, basically). - -```bash -jest -t name-of-spec -``` - -Run watch mode: - -```bash -jest --watch #runs jest -o by default -jest --watchAll #runs all tests -``` - -Watch mode also enables to specify the name or path to a file to focus on a specific set of tests. - -## Using with yarn - -If you run Jest via `yarn test`, you can pass the command line arguments directly as Jest arguments. - -Instead of: - -```bash -jest -u -t="ColorPicker" -``` - -you can use: - -```bash -yarn test -u -t="ColorPicker" -``` - -## Using with npm scripts - -If you run Jest via `npm test`, you can still use the command line arguments by inserting a `--` between `npm test` and the Jest arguments. - -Instead of: - -```bash -jest -u -t="ColorPicker" -``` - -you can use: - -```bash -npm test -- -u -t="ColorPicker" -``` - -## Camelcase & dashed args support - -Jest supports both camelcase and dashed arg formats. The following examples will have an equal result: - -```bash -jest --collect-coverage -jest --collectCoverage -``` - -Arguments can also be mixed: - -```bash -jest --update-snapshot --detectOpenHandles -``` - -## Options - -:::note - -CLI options take precedence over values from the [Configuration](Configuration.md). - -::: - -import TOCInline from '@theme/TOCInline'; - - - ---- - -## Reference - -### `jest ` - -When you run `jest` with an argument, that argument is treated as a regular expression to match against files in your project. It is possible to run test suites by providing a pattern. Only the files that the pattern matches will be picked up and executed. Depending on your terminal, you may need to quote this argument: `jest "my.*(complex)?pattern"`. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. - -### `--bail[=]` - -Alias: `-b`. Exit the test suite immediately upon `n` number of failing test suite. Defaults to `1`. - -### `--cache` - -Whether to use the cache. Defaults to true. Disable the cache using `--no-cache`. - -:::caution - -The cache should only be disabled if you are experiencing caching related problems. On average, disabling the cache makes Jest at least two times slower. - -::: - -If you want to inspect the cache, use `--showConfig` and look at the `cacheDirectory` value. If you need to clear the cache, use `--clearCache`. - -### `--changedFilesWithAncestor` - -Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to `--onlyChanged`. - -### `--changedSince` - -Runs tests related to the changes since the provided branch or commit hash. If the current branch has diverged from the given branch, then only changes made locally will be tested. Behaves similarly to `--onlyChanged`. - -### `--ci` - -When this option is provided, Jest will assume it is running in a CI environment. This changes the behavior when a new snapshot is encountered. Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with `--updateSnapshot`. - -### `--clearCache` - -Deletes the Jest cache directory and then exits without running tests. Will delete `cacheDirectory` if the option is passed, or Jest's default cache directory. The default cache directory can be found by calling `jest --showConfig`. - -:::caution - -Clearing the cache will reduce performance. - -::: - -### `--clearMocks` - -Automatically clear mock calls, instances and results before every test. Equivalent to calling [`jest.clearAllMocks()`](JestObjectAPI.md#jestclearallmocks) before each test. This does not remove any mock implementation that may have been provided. - -### `--collectCoverageFrom=` - -A glob pattern relative to `rootDir` matching the files that coverage info needs to be collected from. - -### `--colors` - -Forces test results output highlighting even if stdout is not a TTY. - -:::note - -Alternatively you can set the environment variable `FORCE_COLOR=true` to forcefully enable or `FORCE_COLOR=false` to disable colorized output. The use of `FORCE_COLOR` overrides all other color support checks. - -::: - -### `--config=` - -Alias: `-c`. The path to a Jest config file specifying how to find and execute tests. If no `rootDir` is set in the config, the directory containing the config file is assumed to be the `rootDir` for the project. This can also be a JSON-encoded value which Jest will use as configuration. - -### `--coverage[=]` - -Alias: `--collectCoverage`. Indicates that test coverage information should be collected and reported in the output. Optionally pass `` to override option set in configuration. - -### `--coverageDirectory=` - -The directory where Jest should output its coverage files. - -### `--coverageProvider=` - -Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. - -:::note - -Using `v8` is considered experimental. This uses V8's builtin code coverage rather than one based on Babel and comes with a few caveats - -1. Your node version must include `vm.compileFunction`, which was introduced in [node 10.10](https://nodejs.org/dist/latest-v12.x/docs/api/vm.html#vm_vm_compilefunction_code_params_options) -1. Tests needs to run in Node test environment (support for `jsdom` requires [`jest-environment-jsdom-sixteen`](https://www.npmjs.com/package/jest-environment-jsdom-sixteen)) -1. V8 has way better data in the later versions, so using the latest versions of node (v13 at the time of this writing) will yield better results - -::: - -### `--debug` - -Print debugging info about your Jest config. - -### `--detectOpenHandles` - -Attempt to collect and print open handles preventing Jest from exiting cleanly. Use this in cases where you need to use `--forceExit` in order for Jest to exit to potentially track down the reason. This implies `--runInBand`, making tests run serially. Implemented using [`async_hooks`](https://nodejs.org/api/async_hooks.html). This option has a significant performance penalty and should only be used for debugging. - -### `--env=` - -The test environment used for all tests. This can point to any file or node module. Examples: `jsdom`, `node` or `path/to/my-environment.js`. - -### `--errorOnDeprecated` - -Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process. - -### `--expand` - -Alias: `-e`. Use this flag to show full diffs and errors instead of a patch. - -### `--filter=` - -Path to a module exporting a filtering function. This method receives a list of tests which can be manipulated to exclude tests from running. Especially useful when used in conjunction with a testing infrastructure to filter known broken. - -### `--findRelatedTests ` - -Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with `--coverage` to include a test coverage for the source files, no duplicate `--collectCoverageFrom` arguments needed. - -### `--forceExit` - -Force Jest to exit after all tests have completed running. This is useful when resources set up by test code cannot be adequately cleaned up. - -:::caution - -This feature is an escape-hatch. If Jest doesn't exit at the end of a test run, it means external resources are still being held on to or timers are still pending in your code. It is advised to tear down external resources after each test to make sure Jest can shut down cleanly. You can use `--detectOpenHandles` to help track it down. - -::: - -### `--help` - -Show the help information, similar to this page. - -### `--init` - -Generate a basic configuration file. Based on your project, Jest will ask you a few questions that will help to generate a `jest.config.js` file with a short description for each option. - -### `--json` - -Prints the test results in JSON. This mode will send all other test output and user messages to stderr. - -### `--outputFile=` - -Write test results to a file when the `--json` option is also specified. The returned JSON structure is documented in [testResultsProcessor](Configuration.md#testresultsprocessor-string). - -### `--lastCommit` - -Run all tests affected by file changes in the last commit made. Behaves similarly to `--onlyChanged`. - -### `--listTests` - -Lists all test files that Jest will run given the arguments, and exits. - -### `--logHeapUsage` - -Logs the heap usage after every test. Useful to debug memory leaks. Use together with `--runInBand` and `--expose-gc` in node. - -### `--maxConcurrency=` - -Prevents Jest from executing more than the specified amount of tests at the same time. Only affects tests that use `test.concurrent`. - -### `--maxWorkers=|` - -Alias: `-w`. Specifies the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases. - -For environments with variable CPUs available, you can use percentage based configuration: `--maxWorkers=50%` - -### `--noStackTrace` - -Disables stack trace in test results output. - -### `--notify` - -Activates notifications for test results. Good for when you don't want your consciousness to be able to focus on anything except JavaScript testing. - -### `--onlyChanged` - -Alias: `-o`. Attempts to identify which tests to run based on which files have changed in the current repository. Only works if you're running tests in a git/hg repository at the moment and requires a static dependency graph (ie. no dynamic requires). - -### `--passWithNoTests` - -Allows the test suite to pass when no files are found. - -### `--projects ... ` - -Run tests from one or more projects, found in the specified paths; also takes path globs. This option is the CLI equivalent of the [`projects`](configuration#projects-arraystring--projectconfig) configuration option. - -:::note - -If configuration files are found in the specified paths, _all_ projects specified within those configuration files will be run. - -::: - -### `--reporters` - -Run tests with specified reporters. [Reporter options](configuration#reporters-arraymodulename--modulename-options) are not available via CLI. Example with multiple reporters: - -`jest --reporters="default" --reporters="jest-junit"` - -### `--resetMocks` - -Automatically reset mock state before every test. Equivalent to calling [`jest.resetAllMocks()`](JestObjectAPI.md#jestresetallmocks) before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation. - -### `--restoreMocks` - -Automatically restore mock state and implementation before every test. Equivalent to calling [`jest.restoreAllMocks()`](JestObjectAPI.md#jestrestoreallmocks) before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation. - -### `--roots` - -A list of paths to directories that Jest should use to search for files in. - -### `--runInBand` - -Alias: `-i`. Run all tests serially in the current process, rather than creating a worker pool of child processes that run tests. This can be useful for debugging. - -### `--runTestsByPath` - -Run only the tests that were specified with their exact paths. - -:::tip - -The default regex matching works fine on small runs, but becomes slow if provided with multiple patterns and/or against a lot of tests. This option replaces the regex matching logic and by that optimizes the time it takes Jest to filter specific test files. - -::: - -### `--setupFilesAfterEnv ... ` - -A list of paths to modules that run some code to configure or to set up the testing framework before each test. Beware that files imported by the setup scripts will not be mocked during testing. - -### `--showConfig` - -Print your Jest config and then exits. - -### `--silent` - -Prevent tests from printing messages through the console. - -### `--testLocationInResults` - -Adds a `location` field to test results. Useful if you want to report the location of a test in a reporter. - -:::note - -In the resulting object `column` is 0-indexed while `line` is not. - -```json -{ - "column": 4, - "line": 5 -} -``` - -::: - -### `--testMatch glob1 ... globN` - -The glob patterns Jest uses to detect test files. Please refer to the [`testMatch` configuration](Configuration.md#testmatch-arraystring) for details. - -### `--testNamePattern=` - -Alias: `-t`. Run only tests with a name that matches the regex. For example, suppose you want to run only tests related to authorization which will have names like `'GET /api/posts with auth'`, then you can use `jest -t=auth`. - -:::tip - -The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks. - -::: - -### `--testPathIgnorePatterns=|[array]` - -A single or array of regexp pattern strings that are tested against all tests paths before executing the test. Contrary to `--testPathPattern`, it will only run those tests with a path that does not match with the provided regexp expressions. - -To pass as an array use escaped parentheses and space delimited regexps such as `\(/node_modules/ /tests/e2e/\)`. Alternatively, you can omit parentheses by combining regexps into a single regexp like `/node_modules/|/tests/e2e/`. These two examples are equivalent. - -### `--testPathPattern=` - -A regexp pattern string that is matched against all tests paths before executing the test. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. - -### `--testRunner=` - -Lets you specify a custom test runner. - -### `--testSequencer=` - -Lets you specify a custom test sequencer. Please refer to the documentation of the corresponding configuration property for details. - -### `--testTimeout=` - -Default timeout of a test in milliseconds. Default value: 5000. - -### `--updateSnapshot` - -Alias: `-u`. Use this flag to re-record every snapshot that fails during this test run. Can be used together with a test suite pattern or with `--testNamePattern` to re-record snapshots. - -### `--useStderr` - -Divert all output to stderr. - -### `--verbose` - -Display individual test results with the test suite hierarchy. - -### `--version` - -Alias: `-v`. Print the version and exit. - -### `--watch` - -Watch files for changes and rerun tests related to changed files. If you want to re-run all tests when a file has changed, use the `--watchAll` option instead. - -:::tip - -Use `--no-watch` (or `--watch=false`) to explicitly disable the watch mode if it was enabled using `--watch`. In most CI environments, this is automatically handled for you. - -::: - -### `--watchAll` - -Watch files for changes and rerun all tests when something changes. If you want to re-run only the tests that depend on the changed files, use the `--watch` option. - -:::tip - -Use `--no-watchAll` (or `--watchAll=false`) to explicitly disable the watch mode if it was enabled using `--watchAll`. In most CI environments, this is automatically handled for you. - -::: - -### `--watchman` - -Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawling. Defaults to `true`. Disable using `--no-watchman`. diff --git a/website/versioned_docs/version-25.x/Configuration.md b/website/versioned_docs/version-25.x/Configuration.md deleted file mode 100644 index 9d85a780abf7..000000000000 --- a/website/versioned_docs/version-25.x/Configuration.md +++ /dev/null @@ -1,1447 +0,0 @@ ---- -id: configuration -title: Configuring Jest ---- - -Jest's configuration can be defined in the `package.json` file of your project, or through a `jest.config.js` file or through the `--config ` option. If you'd like to use your `package.json` to store Jest's config, the `"jest"` key should be used on the top level so Jest will know how to find your settings: - -```json -{ - "name": "my-project", - "jest": { - "verbose": true - } -} -``` - -Or through JavaScript: - -```js title="jest.config.js" -/** @type {import('@jest/types').Config.InitialOptions} */ -const config = { - verbose: true, -}; - -module.exports = config; -``` - -Please keep in mind that the resulting configuration must be JSON-serializable. - -When using the `--config` option, the JSON file must not contain a "jest" key: - -```json -{ - "bail": 1, - "verbose": true -} -``` - -## Options - -These options let you control Jest's behavior in your `package.json` file. The Jest philosophy is to work great by default, but sometimes you just need more configuration power. - -### Defaults - -You can retrieve Jest's default options to expand them if needed: - -```js title="jest.config.js" -const {defaults} = require('jest-config'); -module.exports = { - // ... - moduleFileExtensions: [...defaults.moduleFileExtensions, 'ts', 'tsx'], - // ... -}; -``` - -import TOCInline from '@theme/TOCInline'; - - - ---- - -## Reference - -### `automock` \[boolean] - -Default: `false` - -This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface. - -Example: - -```js title="utils.js" -export default { - authorize: () => { - return 'token'; - }, - isAuthorized: secret => secret === 'wizard', -}; -``` - -```js -//__tests__/automocking.test.js -import utils from '../utils'; - -test('if utils mocked automatically', () => { - // Public methods of `utils` are now mock functions - expect(utils.authorize.mock).toBeTruthy(); - expect(utils.isAuthorized.mock).toBeTruthy(); - - // You can provide them with your own implementation - // or pass the expected return value - utils.authorize.mockReturnValue('mocked_token'); - utils.isAuthorized.mockReturnValue(true); - - expect(utils.authorize()).toBe('mocked_token'); - expect(utils.isAuthorized('not_wizard')).toBeTruthy(); -}); -``` - -:::note - -Node modules are automatically mocked when you have a manual mock in place (e.g.: `__mocks__/lodash.js`). More info [here](ManualMocks.md#mocking-node-modules). - -Node.js core modules, like `fs`, are not mocked by default. They can be mocked explicitly, like `jest.mock('fs')`. - -::: - -### `bail` \[number | boolean] - -Default: `0` - -By default, Jest runs all tests and produces all errors into the console upon completion. The bail config option can be used here to have Jest stop running tests after `n` failures. Setting bail to `true` is the same as setting bail to `1`. - -### `browser` \[boolean] - -Default: `false` - -Respect Browserify's [`"browser"` field](https://github.com/browserify/browserify-handbook/blob/master/readme.markdown#browser-field) in `package.json` when resolving modules. Some modules export different versions based on whether they are operating in Node or a browser. - -### `cacheDirectory` \[string] - -Default: `"/tmp/"` - -The directory where Jest should store its cached dependency information. - -Jest attempts to scan your dependency tree once (up-front) and cache it in order to ease some of the filesystem churn that needs to happen while running tests. This config option lets you customize where Jest stores that cache data on disk. - -### `clearMocks` \[boolean] - -Default: `false` - -Automatically clear mock calls, instances and results before every test. Equivalent to calling [`jest.clearAllMocks()`](JestObjectAPI.md#jestclearallmocks) before each test. This does not remove any mock implementation that may have been provided. - -### `collectCoverage` \[boolean] - -Default: `false` - -Indicates whether the coverage information should be collected while executing the test. Because this retrofits all executed files with coverage collection statements, it may significantly slow down your tests. - -Jest ships with two coverage providers: `babel` (default) and `v8`. See the [`coverageProvider`](#coverageprovider-string) option for more details. - -:::info - -The `babel` and `v8` coverage providers use `/* istanbul ignore next */` and `/* c8 ignore next */` comments to exclude lines from coverage reports, respectively. For more information, you can view the [`istanbuljs` documentation](https://github.com/istanbuljs/nyc#parsing-hints-ignoring-lines) and the [`c8` documentation](https://github.com/bcoe/c8#ignoring-uncovered-lines-functions-and-blocks). - -::: - -### `collectCoverageFrom` \[array] - -Default: `undefined` - -An array of [glob patterns](https://github.com/micromatch/micromatch) indicating a set of files for which coverage information should be collected. If a file matches the specified glob pattern, coverage information will be collected for it even if no tests exist for this file and it's never required in the test suite. - -Example: - -```json -{ - "collectCoverageFrom": [ - "**/*.{js,jsx}", - "!**/node_modules/**", - "!**/vendor/**" - ] -} -``` - -This will collect coverage information for all the files inside the project's `rootDir`, except the ones that match `**/node_modules/**` or `**/vendor/**`. - -:::tip - -Each glob pattern is applied in the order they are specified in the config. For example `["!**/__tests__/**", "**/*.js"]` will not exclude `__tests__` because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after `**/*.js`. - -::: - -:::note - -This option requires `collectCoverage` to be set to `true` or Jest to be invoked with `--coverage`. - -::: - -
- Help: - If you are seeing coverage output such as... - -``` -=============================== Coverage summary =============================== -Statements : Unknown% ( 0/0 ) -Branches : Unknown% ( 0/0 ) -Functions : Unknown% ( 0/0 ) -Lines : Unknown% ( 0/0 ) -================================================================================ -Jest: Coverage data for global was not found. -``` - -Most likely your glob patterns are not matching any files. Refer to the [micromatch](https://github.com/micromatch/micromatch) documentation to ensure your globs are compatible. - -
- -### `coverageDirectory` \[string] - -Default: `undefined` - -The directory where Jest should output its coverage files. - -### `coveragePathIgnorePatterns` \[array<string>] - -Default: `["/node_modules/"]` - -An array of regexp pattern strings that are matched against all file paths before executing the test. If the file path matches any of the patterns, coverage information will be skipped. - -These pattern strings match against the full path. Use the `` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `["/build/", "/node_modules/"]`. - -### `coverageProvider` \[string] - -Indicates which provider should be used to instrument code for coverage. Allowed values are `babel` (default) or `v8`. - -:::note - -Using `v8` is considered experimental. This uses V8's builtin code coverage rather than one based on Babel and comes with a few caveats - -1. Your node version must include `vm.compileFunction`, which was introduced in [node 10.10](https://nodejs.org/dist/latest-v12.x/docs/api/vm.html#vm_vm_compilefunction_code_params_options) -1. Tests needs to run in Node test environment (support for `jsdom` requires [`jest-environment-jsdom-sixteen`](https://www.npmjs.com/package/jest-environment-jsdom-sixteen)) -1. V8 has way better data in the later versions, so using the latest versions of node (v13 at the time of this writing) will yield better results - -:::note - -### `coverageReporters` \[array<string | \[string, options]>] - -Default: `["clover", "json", "lcov", "text"]` - -A list of reporter names that Jest uses when writing coverage reports. Any [istanbul reporter](https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib) can be used. - -:::tip - -Setting this option overwrites the default values. Add `"text"` or `"text-summary"` to see a coverage summary in the console output. - -::: - -Additional options can be passed using the tuple form. For example, you may hide coverage report lines for all fully-covered files: - -```json -{ - "coverageReporters": ["clover", "json", "lcov", ["text", {"skipFull": true}]] -} -``` - -For more information about the options object shape refer to `CoverageReporterWithOptions` type in the [type definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Config.ts). - -### `coverageThreshold` \[object] - -Default: `undefined` - -This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as `global`, as a [glob](https://github.com/isaacs/node-glob#glob-primer), and as a directory or file path. If thresholds aren't met, jest will fail. Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed. - -For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements: - -```json -{ - ... - "jest": { - "coverageThreshold": { - "global": { - "branches": 80, - "functions": 80, - "lines": 80, - "statements": -10 - } - } - } -} -``` - -If globs or paths are specified alongside `global`, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. Thresholds for globs are applied to all files matching the glob. If the file specified by path is not found, an error is returned. - -For example, with the following configuration: - -```json -{ - ... - "jest": { - "coverageThreshold": { - "global": { - "branches": 50, - "functions": 50, - "lines": 50, - "statements": 50 - }, - "./src/components/": { - "branches": 40, - "statements": 40 - }, - "./src/reducers/**/*.js": { - "statements": 90 - }, - "./src/api/very-important-module.js": { - "branches": 100, - "functions": 100, - "lines": 100, - "statements": 100 - } - } - } -} -``` - -Jest will fail if: - -- The `./src/components` directory has less than 40% branch or statement coverage. -- One of the files matching the `./src/reducers/**/*.js` glob has less than 90% statement coverage. -- The `./src/api/very-important-module.js` file has less than 100% coverage. -- Every remaining file combined has less than 50% coverage (`global`). - -### `dependencyExtractor` \[string] - -Default: `undefined` - -This option allows the use of a custom dependency extractor. It must be a node module that exports an object with an `extract` function. E.g.: - -```javascript -const crypto = require('crypto'); -const fs = require('fs'); - -module.exports = { - extract(code, filePath, defaultExtract) { - const deps = defaultExtract(code, filePath); - // Scan the file and add dependencies in `deps` (which is a `Set`) - return deps; - }, - getCacheKey() { - return crypto - .createHash('md5') - .update(fs.readFileSync(__filename)) - .digest('hex'); - }, -}; -``` - -The `extract` function should return an iterable (`Array`, `Set`, etc.) with the dependencies found in the code. - -That module can also contain a `getCacheKey` function to generate a cache key to determine if the logic has changed and any cached artifacts relying on it should be discarded. - -### `displayName` \[string, object] - -default: `undefined` - -Allows for a label to be printed alongside a test while it is running. This becomes more useful in multi-project repositories where there can be many jest configuration files. This visually tells which project a test belongs to. Here are sample valid values. - -```js -module.exports = { - displayName: 'CLIENT', -}; -``` - -or - -```js -module.exports = { - displayName: { - name: 'CLIENT', - color: 'blue', - }, -}; -``` - -As a secondary option, an object with the properties `name` and `color` can be passed. This allows for a custom configuration of the background color of the displayName. `displayName` defaults to white when its value is a string. Jest uses [chalk](https://github.com/chalk/chalk) to provide the color. As such, all of the valid options for colors supported by chalk are also supported by jest. - -### `errorOnDeprecated` \[boolean] - -Default: `false` - -Make calling deprecated APIs throw helpful error messages. Useful for easing the upgrade process. - -### `extraGlobals` \[array<string>] - -Default: `undefined` - -Test files run inside a [vm](https://nodejs.org/api/vm.html), which slows calls to global context properties (e.g. `Math`). With this option you can specify extra properties to be defined inside the vm for faster lookups. - -For example, if your tests call `Math` often, you can pass it by setting `extraGlobals`. - -```json -{ - ... - "jest": { - "extraGlobals": ["Math"] - } -} -``` - -### `forceCoverageMatch` \[array<string>] - -Default: `['']` - -Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage. - -For example, if you have tests in source files named with `.t.js` extension as following: - -```javascript title="sum.t.js" -export function sum(a, b) { - return a + b; -} - -if (process.env.NODE_ENV === 'test') { - test('sum', () => { - expect(sum(1, 2)).toBe(3); - }); -} -``` - -You can collect coverage from those files with setting `forceCoverageMatch`. - -```json -{ - ... - "jest": { - "forceCoverageMatch": ["**/*.t.js"] - } -} -``` - -### `globals` \[object] - -Default: `{}` - -A set of global variables that need to be available in all test environments. - -For example, the following would create a global `__DEV__` variable set to `true` in all test environments: - -```json -{ - ... - "jest": { - "globals": { - "__DEV__": true - } - } -} -``` - -:::info - -If you specify a global reference value (like an object or array) here, and some code mutates that value in the midst of running a test, that mutation will _not_ be persisted across test runs for other test files. In addition, the `globals` object must be json-serializable, so it can't be used to specify global functions. For that, you should use `setupFiles`. - -::: - -### `globalSetup` \[string] - -Default: `undefined` - -This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) object as a parameter. - -:::info - -A global setup module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project. - -Any global variables that are defined through `globalSetup` can only be read in `globalTeardown`. You cannot retrieve globals defined here in your test suites. - -While code transformation is applied to the linked setup-file, Jest will **not** transform any code in `node_modules`. This is due to the need to load the actual transformers (e.g. `babel` or `typescript`) to perform transformation. - -::: - -```js title="setup.js" -// can be synchronous -module.exports = async () => { - // ... - // Set reference to mongod in order to close the server during teardown. - global.__MONGOD__ = mongod; -}; -``` - -```js title="teardown.js" -module.exports = async function () { - await global.__MONGOD__.stop(); -}; -``` - -### `globalTeardown` \[string] - -Default: `undefined` - -This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. This function gets Jest's [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) object as a parameter. - -:::info - -A global teardown module configured in a project (using multi-project runner) will be triggered only when you run at least one test from this project. - -The same caveat concerning transformation of `node_modules` as for `globalSetup` applies to `globalTeardown`. - -::: - -### `haste` \[object] - -Default: `undefined` - -This will be used to configure the behavior of `jest-haste-map`, Jest's internal file crawler/cache system. The following options are supported: - -```ts -type HasteConfig = { - // Whether to hash files using SHA-1. - computeSha1?: boolean; - // The platform to use as the default, e.g. 'ios'. - defaultPlatform?: string | null; - // Path to a custom implementation of Haste. - hasteImplModulePath?: string; - // All platforms to target, e.g ['ios', 'android']. - platforms?: Array; - // Whether to throw on error on module collision. - throwOnModuleCollision?: boolean; -}; -``` - -### `maxConcurrency` \[number] - -Default: `5` - -A number limiting the number of tests that are allowed to run at the same time when using `test.concurrent`. Any test above this limit will be queued and executed once a slot is released. - -### `maxWorkers` \[number | string] - -Specifies the maximum number of workers the worker-pool will spawn for running tests. In single run mode, this defaults to the number of the cores available on your machine minus one for the main thread. In watch mode, this defaults to half of the available cores on your machine to ensure Jest is unobtrusive and does not grind your machine to a halt. It may be useful to adjust this in resource limited environments like CIs but the defaults should be adequate for most use-cases. - -For environments with variable CPUs available, you can use percentage based configuration: `"maxWorkers": "50%"` - -### `moduleDirectories` \[array<string>] - -Default: `["node_modules"]` - -An array of directory names to be searched recursively up from the requiring module's location. Setting this option will _override_ the default, if you wish to still search `node_modules` for packages include it along with any other options: `["node_modules", "bower_components"]` - -### `moduleFileExtensions` \[array<string>] - -Default: `["js", "json", "jsx", "ts", "tsx", "node"]` - -An array of file extensions your modules use. If you require modules without specifying a file extension, these are the extensions Jest will look for, in left-to-right order. - -We recommend placing the extensions most commonly used in your project on the left, so if you are using TypeScript, you may want to consider moving "ts" and/or "tsx" to the beginning of the array. - -### `moduleNameMapper` \[object<string, string | array<string>>] - -Default: `null` - -A map from regular expressions to module names or to arrays of module names that allow to stub out resources, like images or styles with a single module. - -Modules that are mapped to an alias are unmocked by default, regardless of whether automocking is enabled or not. - -Use `` string token to refer to [`rootDir`](#rootdir-string) value if you want to use file paths. - -Additionally, you can substitute captured regex groups using numbered backreferences. - -Example: - -```json -{ - "moduleNameMapper": { - "^image![a-zA-Z0-9$_-]+$": "GlobalImageStub", - "^[./a-zA-Z0-9$_-]+\\.png$": "/RelativeImageStub.js", - "module_name_(.*)": "/substituted_module_$1.js", - "assets/(.*)": [ - "/images/$1", - "/photos/$1", - "/recipes/$1" - ] - } -} -``` - -The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. This is true for arrays of module names as well. - -:::info - -If you provide module names without boundaries `^$` it may cause hard to spot errors. E.g. `relay` will replace all modules which contain `relay` as a substring in its name: `relay`, `react-relay` and `graphql-relay` will all be pointed to your stub. - -::: - -### `modulePathIgnorePatterns` \[array<string>] - -Default: `[]` - -An array of regexp pattern strings that are matched against all module paths before those paths are to be considered 'visible' to the module loader. If a given module's path matches any of the patterns, it will not be `require()`-able in the test environment. - -These pattern strings match against the full path. Use the `` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `["/build/"]`. - -### `modulePaths` \[array<string>] - -Default: `[]` - -An alternative API to setting the `NODE_PATH` env variable, `modulePaths` is an array of absolute paths to additional locations to search when resolving modules. Use the `` string token to include the path to your project's root directory. Example: `["/app/"]`. - -### `notify` \[boolean] - -Default: `false` - -Activates native OS notifications for test results. To display the notifications Jest needs [`node-notifier`](https://github.com/mikaelbr/node-notifier) package, which must be installed additionally: - -```bash npm2yarn -npm install --save-dev node-notifier -``` - -:::tip - -On macOS, remember to allow notifications from `terminal-notifier` under System Preferences > Notifications & Focus. - -On Windows, `node-notifier` creates a new start menu entry on the first use and not display the notification. Notifications will be properly displayed on subsequent runs. - -::: - -### `notifyMode` \[string] - -Default: `failure-change` - -Specifies notification mode. Requires `notify: true`. - -#### Modes - -- `always`: always send a notification. -- `failure`: send a notification when tests fail. -- `success`: send a notification when tests pass. -- `change`: send a notification when the status changed. -- `success-change`: send a notification when tests pass or once when it fails. -- `failure-change`: send a notification when tests fail or once when it passes. - -### `preset` \[string] - -Default: `undefined` - -A preset that is used as a base for Jest's configuration. A preset should point to an npm module that has a `jest-preset.json` or `jest-preset.js` file at the root. - -For example, this preset `foo-bar/jest-preset.js` will be configured as follows: - -```json -{ - "preset": "foo-bar" -} -``` - -Presets may also be relative to filesystem paths. - -```json -{ - "preset": "./node_modules/foo-bar/jest-preset.js" -} -``` - -:::info - -If you also have specified [`rootDir`](#rootdir-string), the resolution of this file will be relative to that root directory. - -::: - -### `prettierPath` \[string] - -Default: `'prettier'` - -Sets the path to the [`prettier`](https://prettier.io/) node module used to update inline snapshots. - -### `projects` \[array<string | ProjectConfig>] - -Default: `undefined` - -When the `projects` configuration is provided with an array of paths or glob patterns, Jest will run tests in all of the specified projects at the same time. This is great for monorepos or when working on multiple projects at the same time. - -```json -{ - "projects": ["", "/examples/*"] -} -``` - -This example configuration will run Jest in the root directory as well as in every folder in the examples directory. You can have an unlimited amount of projects running in the same Jest instance. - -The projects feature can also be used to run multiple configurations or multiple [runners](#runner-string). For this purpose, you can pass an array of configuration objects. For example, to run both tests and ESLint (via [jest-runner-eslint](https://github.com/jest-community/jest-runner-eslint)) in the same invocation of Jest: - -```json -{ - "projects": [ - { - "displayName": "test" - }, - { - "displayName": "lint", - "runner": "jest-runner-eslint", - "testMatch": ["/**/*.js"] - } - ] -} -``` - -:::tip - -When using multi-project runner, it's recommended to add a `displayName` for each project. This will show the `displayName` of a project next to its tests. - -::: - -:::note - -With the `projects` option enabled, Jest will copy the root-level configuration options to each individual child configuration during the test run, resolving its values in the child's context. This means that string tokens like `` will point to the _child's root directory_ even if they are defined in the root-level configuration. - -::: - -### `reporters` \[array<moduleName | \[moduleName, options]>] - -Default: `undefined` - -Use this configuration option to add custom reporters to Jest. A custom reporter is a class that implements `onRunStart`, `onTestStart`, `onTestResult`, `onRunComplete` methods that will be called when any of those events occurs. - -If custom reporters are specified, the default Jest reporters will be overridden. To keep default reporters, `default` can be passed as a module name. - -This will override default reporters: - -```json -{ - "reporters": ["/my-custom-reporter.js"] -} -``` - -This will use custom reporter in addition to default reporters that Jest provides: - -```json -{ - "reporters": ["default", "/my-custom-reporter.js"] -} -``` - -Additionally, custom reporters can be configured by passing an `options` object as a second argument: - -```json -{ - "reporters": [ - "default", - ["/my-custom-reporter.js", {"banana": "yes", "pineapple": "no"}] - ] -} -``` - -Custom reporter modules must define a class that takes a [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) and reporter options as constructor arguments: - -Example reporter: - -```js title="my-custom-reporter.js" -class MyCustomReporter { - constructor(globalConfig, options) { - this._globalConfig = globalConfig; - this._options = options; - } - - onRunComplete(contexts, results) { - console.log('Custom reporter output:'); - console.log('GlobalConfig: ', this._globalConfig); - console.log('Options: ', this._options); - } -} - -module.exports = MyCustomReporter; -// or export default MyCustomReporter; -``` - -Custom reporters can also force Jest to exit with non-0 code by returning an Error from `getLastError()` methods - -```js -class MyCustomReporter { - // ... - getLastError() { - if (this._shouldFail) { - return new Error('my-custom-reporter.js reported an error'); - } - } -} -``` - -For the full list of methods and argument types see `Reporter` interface in [packages/jest-reporters/src/types.ts](https://github.com/jestjs/jest/blob/main/packages/jest-reporters/src/types.ts) - -### `resetMocks` \[boolean] - -Default: `false` - -Automatically reset mock state before every test. Equivalent to calling [`jest.resetAllMocks()`](JestObjectAPI.md#jestresetallmocks) before each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation. - -### `resetModules` \[boolean] - -Default: `false` - -By default, each test file gets its own independent module registry. Enabling `resetModules` goes a step further and resets the module registry before running each individual test. This is useful to isolate modules for every test so that the local module state doesn't conflict between tests. This can be done programmatically using [`jest.resetModules()`](JestObjectAPI.md#jestresetmodules). - -### `resolver` \[string] - -Default: `undefined` - -This option allows the use of a custom resolver. This resolver must be a node module that exports a function expecting a string as the first argument for the path to resolve and an object with the following structure as the second argument: - -```json -{ - "basedir": string, - "browser": boolean, - "defaultResolver": "function(request, options)", - "extensions": [string], - "moduleDirectory": [string], - "paths": [string], - "rootDir": [string] -} -``` - -The function should either return a path to the module that should be resolved or throw an error if the module can't be found. - -:::tip - -The `defaultResolver` passed as an option is the Jest default resolver which might be useful when you write your custom one. It takes the same arguments as your custom one, e.g. `(request, options)`. - -::: - -### `restoreMocks` \[boolean] - -Default: `false` - -Automatically restore mock state and implementation before every test. Equivalent to calling [`jest.restoreAllMocks()`](JestObjectAPI.md#jestrestoreallmocks) before each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation. - -### `rootDir` \[string] - -Default: The root of the directory containing your Jest [config file](#) _or_ the `package.json` _or_ the [`pwd`](http://en.wikipedia.org/wiki/Pwd) if no `package.json` is found - -The root directory that Jest should scan for tests and modules within. If you put your Jest config inside your `package.json` and want the root directory to be the root of your repo, the value for this config param will default to the directory of the `package.json`. - -Oftentimes, you'll want to set this to `'src'` or `'lib'`, corresponding to where in your repository the code is stored. - -:::tip - -Using `''` as a string token in any other path-based configuration settings will refer back to this value. For example, if you want a [`setupFiles`](#setupfiles-array) entry to point at the `some-setup.js` file at the root of the project, set its value to: `'/some-setup.js'`. - -::: - -### `roots` \[array<string>] - -Default: `[""]` - -A list of paths to directories that Jest should use to search for files in. - -There are times where you only want Jest to search in a single sub-directory (such as cases where you have a `src/` directory in your repo), but prevent it from accessing the rest of the repo. - -:::info - -While `rootDir` is mostly used as a token to be re-used in other configuration options, `roots` is used by the internals of Jest to locate **test files and source files**. This applies also when searching for manual mocks for modules from `node_modules` (`__mocks__` will need to live in one of the `roots`). - -By default, `roots` has a single entry `` but there are cases where you may want to have multiple roots within one project, for example `roots: ["/src/", "/tests/"]`. - -::: - -### `runner` \[string] - -Default: `"jest-runner"` - -This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include: - -- [`jest-runner-eslint`](https://github.com/jest-community/jest-runner-eslint) -- [`jest-runner-mocha`](https://github.com/rogeliog/jest-runner-mocha) -- [`jest-runner-tsc`](https://github.com/azz/jest-runner-tsc) -- [`jest-runner-prettier`](https://github.com/keplersj/jest-runner-prettier) - -:::info - -The `runner` property value can omit the `jest-runner-` prefix of the package name. - -::: - -To write a test-runner, export a class with which accepts [`globalConfig`](https://github.com/jestjs/jest/blob/v25.5.4/packages/jest-types/src/Config.ts#L234-L300) in the constructor, and has a `runTests` method with the signature: - -```ts -async function runTests( - tests: Array, - watcher: TestWatcher, - onStart: OnTestStart, - onResult: OnTestSuccess, - onFailure: OnTestFailure, - options: TestRunnerOptions, -): Promise; -``` - -If you need to restrict your test-runner to only run in serial rather than being executed in parallel your class should have the property `isSerial` to be set as `true`. - -### `setupFiles` \[array] - -Default: `[]` - -A list of paths to modules that run some code to configure or set up the testing environment. Each setupFile will be run once per test file. Since every test runs in its own environment, these scripts will be executed in the testing environment before executing [`setupFilesAfterEnv`](#setupfilesafterenv-array) and before the test code itself. - -### `setupFilesAfterEnv` \[array] - -Default: `[]` - -:::info - -Renamed from `setupTestFrameworkScriptFile` in Jest 24. - -::: - -A list of paths to modules that run some code to configure or set up the testing framework before each test file in the suite is executed. Since [`setupFiles`](#setupfiles-array) executes before the test framework is installed in the environment, this script file presents you the opportunity of running some code immediately after the test framework has been installed in the environment but before the test code itself. - -In other words, `setupFilesAfterEnv` modules are meant for code which is repeating in each test files. Having the test framework installed makes Jest [globals](GlobalAPI.md), [`jest` object](JestObjectAPI.md) and [`expect`](ExpectAPI.md) accessible in the modules. For example, you can add extra matchers from [`jest-extended`](https://github.com/jest-community/jest-extended) library or call [setup and teardown](SetupAndTeardown.md) hooks: - -```js title="setup-jest.js" -const matchers = require('jest-extended'); -expect.extend(matchers); - -afterEach(() => { - jest.useRealTimers(); -}); -``` - -```js -module.exports = { - setupFilesAfterEnv: ['/setup-jest.js'], -}; -``` - -### `snapshotResolver` \[string] - -Default: `undefined` - -The path to a module that can resolve test<->snapshot path. This config option lets you customize where Jest stores snapshot files on disk. - -Example snapshot resolver module: - -```js -module.exports = { - // resolves from test to snapshot path - resolveSnapshotPath: (testPath, snapshotExtension) => - testPath.replace('__tests__', '__snapshots__') + snapshotExtension, - - // resolves from snapshot to test path - resolveTestPath: (snapshotFilePath, snapshotExtension) => - snapshotFilePath - .replace('__snapshots__', '__tests__') - .slice(0, -snapshotExtension.length), - - // Example test path, used for preflight consistency check of the implementation above - testPathForConsistencyCheck: 'some/__tests__/example.test.js', -}; -``` - -### `snapshotSerializers` \[array<string>] - -Default: `[]` - -A list of paths to snapshot serializer modules Jest should use for snapshot testing. - -Jest has default serializers for built-in JavaScript types, HTML elements (Jest 20.0.0+), ImmutableJS (Jest 20.0.0+) and for React elements. See [snapshot test tutorial](TutorialReactNative.md#snapshot-test) for more information. - -Example serializer module: - -```js -// my-serializer-module -module.exports = { - serialize(val, config, indentation, depth, refs, printer) { - return `Pretty foo: ${printer(val.foo)}`; - }, - - test(val) { - return val && Object.prototype.hasOwnProperty.call(val, 'foo'); - }, -}; -``` - -`printer` is a function that serializes a value using existing plugins. - -To use `my-serializer-module` as a serializer, configuration would be as follows: - -```json -{ - ... - "jest": { - "snapshotSerializers": ["my-serializer-module"] - } -} -``` - -Finally tests would look as follows: - -```js -test(() => { - const bar = { - foo: { - x: 1, - y: 2, - }, - }; - - expect(bar).toMatchSnapshot(); -}); -``` - -Rendered snapshot: - -```json -Pretty foo: Object { - "x": 1, - "y": 2, -} -``` - -:::tip - -To make a dependency explicit instead of implicit, you can call [`expect.addSnapshotSerializer`](ExpectAPI.md#expectaddsnapshotserializerserializer) to add a module for an individual test file instead of adding its path to `snapshotSerializers` in Jest configuration. - -More about serializers API can be found [here](https://github.com/jestjs/jest/tree/main/packages/pretty-format/README.md#serialize). - -::: - -### `testEnvironment` \[string] - -Default: `"jsdom"` - -The test environment that will be used for testing. The default environment in Jest is a browser-like environment through [jsdom](https://github.com/jsdom/jsdom). If you are building a node service, you can use the `node` option to use a node-like environment instead. - -By adding a `@jest-environment` docblock at the top of the file, you can specify another environment to be used for all tests in that file: - -```js -/** - * @jest-environment jsdom - */ - -test('use jsdom in this test file', () => { - const element = document.createElement('div'); - expect(element).not.toBeNull(); -}); -``` - -You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. - -The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/jestjs/jest/tree/main/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/jestjs/jest/tree/main/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases. - -Any docblock pragmas in test files will be passed to the environment constructor and can be used for per-test configuration. If the pragma does not have a value, it will be present in the object with its value set to an empty string. If the pragma is not present, it will not be present in the object. - -To use this class as your custom environment, refer to it by its full path within the project. For example, if your class is stored in `my-custom-environment.js` in some subfolder of your project, then the annotation might look like this: - -```js -/** - * @jest-environment ./src/test/my-custom-environment - */ -``` - -:::info - -TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment. - -::: - -Example: - -```js -// my-custom-environment -const NodeEnvironment = require('jest-environment-node'); - -class CustomEnvironment extends NodeEnvironment { - constructor(config, context) { - super(config, context); - this.testPath = context.testPath; - this.docblockPragmas = context.docblockPragmas; - } - - async setup() { - await super.setup(); - await someSetupTasks(this.testPath); - this.global.someGlobalObject = createGlobalObject(); - - // Will trigger if docblock contains @my-custom-pragma my-pragma-value - if (this.docblockPragmas['my-custom-pragma'] === 'my-pragma-value') { - // ... - } - } - - async teardown() { - this.global.someGlobalObject = destroyGlobalObject(); - await someTeardownTasks(); - await super.teardown(); - } - - runScript(script) { - return super.runScript(script); - } - - async handleTestEvent(event, state) { - if (event.name === 'test_start') { - // ... - } - } -} - -module.exports = CustomEnvironment; -``` - -```js -// my-test-suite -/** - * @jest-environment ./my-custom-environment - */ -let someGlobalObject; - -beforeAll(() => { - someGlobalObject = global.someGlobalObject; -}); -``` - -### `testEnvironmentOptions` \[Object] - -Default: `{}` - -Test environment options that will be passed to the `testEnvironment`. The relevant options depend on the environment. - -For example, you can override options passed to [`jsdom`](https://github.com/jsdom/jsdom): - -```js -module.exports = { - testEnvironment: 'jsdom', - testEnvironmentOptions: { - html: '', - userAgent: 'Agent/007', - }, -}; -``` - -### `testFailureExitCode` \[number] - -Default: `1` - -The exit code Jest returns on test failure. - -:::info - -This does not change the exit code in the case of Jest errors (e.g. invalid configuration). - -::: - -### `testMatch` \[array<string>] - -(default: `[ "**/__tests__/**/*.[jt]s?(x)", "**/?(*.)+(spec|test).[jt]s?(x)" ]`) - -The glob patterns Jest uses to detect test files. By default it looks for `.js`, `.jsx`, `.ts` and `.tsx` files inside of `__tests__` folders, as well as any files with a suffix of `.test` or `.spec` (e.g. `Component.test.js` or `Component.spec.js`). It will also find files called `test.js` or `spec.js`. - -See the [micromatch](https://github.com/micromatch/micromatch) package for details of the patterns you can specify. - -See also [`testRegex` [string | array<string>]](#testregex-string--arraystring), but note that you cannot specify both options. - -:::tip - -Each glob pattern is applied in the order they are specified in the config. For example `["!**/__fixtures__/**", "**/__tests__/**/*.js"]` will not exclude `__fixtures__` because the negation is overwritten with the second pattern. In order to make the negated glob work in this example it has to come after `**/__tests__/**/*.js`. - -::: - -### `testPathIgnorePatterns` \[array<string>] - -Default: `["/node_modules/"]` - -An array of regexp pattern strings that are matched against all test paths before executing the test. If the test path matches any of the patterns, it will be skipped. - -These pattern strings match against the full path. Use the `` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `["/build/", "/node_modules/"]`. - -### `testRegex` \[string | array<string>] - -Default: `(/__tests__/.*|(\\.|/)(test|spec))\\.[jt]sx?$` - -The pattern or patterns Jest uses to detect test files. By default it looks for `.js`, `.jsx`, `.ts` and `.tsx` files inside of `__tests__` folders, as well as any files with a suffix of `.test` or `.spec` (e.g. `Component.test.js` or `Component.spec.js`). It will also find files called `test.js` or `spec.js`. See also [`testMatch` [array<string>]](#testmatch-arraystring), but note that you cannot specify both options. - -The following is a visualization of the default regex: - -```bash -├── __tests__ -│ └── component.spec.js # test -│ └── anything # test -├── package.json # not test -├── foo.test.js # test -├── bar.spec.jsx # test -└── component.js # not test -``` - -:::info - -`testRegex` will try to detect test files using the **absolute file path**, therefore, having a folder with a name that matches it will run all the files as tests. - -::: - -### `testResultsProcessor` \[string] - -Default: `undefined` - -This option allows the use of a custom results processor. This processor must be a node module that exports a function expecting an object with the following structure as the first argument and return it: - -```json -{ - "success": boolean, - "startTime": epoch, - "numTotalTestSuites": number, - "numPassedTestSuites": number, - "numFailedTestSuites": number, - "numRuntimeErrorTestSuites": number, - "numTotalTests": number, - "numPassedTests": number, - "numFailedTests": number, - "numPendingTests": number, - "numTodoTests": number, - "openHandles": Array, - "testResults": [{ - "numFailingTests": number, - "numPassingTests": number, - "numPendingTests": number, - "testResults": [{ - "title": string (message in it block), - "status": "failed" | "pending" | "passed", - "ancestorTitles": [string (message in describe blocks)], - "failureMessages": [string], - "numPassingAsserts": number, - "location": { - "column": number, - "line": number - } - }, - ... - ], - "perfStats": { - "start": epoch, - "end": epoch - }, - "testFilePath": absolute path to test file, - "coverage": {} - }, - "testExecError:" (exists if there was a top-level failure) { - "message": string - "stack": string - } - ... - ] -} -``` - -`testResultsProcessor` and `reporters` are very similar to each other. One difference is that a test result processor only gets called after all tests finished. Whereas a reporter has the ability to receive test results after individual tests and/or test suites are finished. - -### `testRunner` \[string] - -Default: `jasmine2` - -This option allows the use of a custom test runner. The default is jasmine2. A custom test runner can be provided by specifying a path to a test runner implementation. - -The test runner module must export a function with the following signature: - -```ts -function testRunner( - globalConfig: GlobalConfig, - config: ProjectConfig, - environment: Environment, - runtime: Runtime, - testPath: string, -): Promise; -``` - -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/jestjs/jest/blob/main/packages/jest-jasmine2/src/index.ts). - -### `testSequencer` \[string] - -Default: `@jest/test-sequencer` - -This option allows you to use a custom sequencer instead of Jest's default. `sort` may optionally return a Promise. - -Example: - -Sort test path alphabetically. - -```js title="testSequencer.js" -const Sequencer = require('@jest/test-sequencer').default; - -class CustomSequencer extends Sequencer { - sort(tests) { - // Test structure information - // https://github.com/jestjs/jest/blob/6b8b1404a1d9254e7d5d90a8934087a9c9899dab/packages/jest-runner/src/types.ts#L17-L21 - const copyTests = Array.from(tests); - return copyTests.sort((testA, testB) => (testA.path > testB.path ? 1 : -1)); - } -} - -module.exports = CustomSequencer; -``` - -Use it in your Jest config file like this: - -```json -{ - "testSequencer": "path/to/testSequencer.js" -} -``` - -### `testTimeout` \[number] - -Default: `5000` - -Default timeout of a test in milliseconds. - -### `testURL` \[string] - -Default: `http://localhost` - -This option sets the URL for the jsdom environment. It is reflected in properties such as `location.href`. - -### `timers` \[string] - -Default: `real` - -Setting this value to `legacy` or `fake` enables fake timers for all tests by default. Fake timers are useful when a piece of code sets a long timeout that we don't want to wait for in a test. You can learn more about fake timers [here](JestObjectAPI.md#jestusefaketimers). - -### `transform` \[object<string, pathToTransformer | \[pathToTransformer, object]>] - -Default: `{"^.+\\.[jt]sx?$": "babel-jest"}` - -A map from regular expressions to paths to transformers. A transformer is a module that provides a synchronous function for transforming source files. For example, if you wanted to be able to use a new language feature in your modules or tests that aren't yet supported by node, you might plug in one of many compilers that compile a future version of JavaScript to a current one. Example: see the [examples/typescript](https://github.com/jestjs/jest/blob/main/examples/typescript/package.json#L16) example or the [webpack tutorial](Webpack.md). - -Examples of such compilers include: - -- [Babel](https://babeljs.io/) -- [TypeScript](http://www.typescriptlang.org/) -- [async-to-gen](http://github.com/leebyron/async-to-gen#jest) -- To build your own please visit the [Custom Transformer](TutorialReact.md#custom-transformers) section - -You can pass configuration to a transformer like `{filePattern: ['path-to-transformer', {options}]}` For example, to configure babel-jest for non-default behavior, `{"\\.js$": ['babel-jest', {rootMode: "upward"}]}` - -:::tip - -A transformer is only run once per file unless the file has changed. During the development of a transformer it can be useful to run Jest with `--no-cache` to frequently [delete Jest's cache](Troubleshooting.md#caching-issues). - -::: - -:::note - -When adding additional code transformers, this will overwrite the default config and `babel-jest` is no longer automatically loaded. If you want to use it to compile JavaScript or Typescript, it has to be explicitly defined by adding `{"\\.[jt]sx?$": "babel-jest"}` to the transform property. See [babel-jest plugin](https://github.com/jestjs/jest/tree/main/packages/babel-jest#setup). - -::: - -### `transformIgnorePatterns` \[array<string>] - -Default: `["/node_modules/", "\\.pnp\\.[^\\\/]+$"]` - -An array of regexp pattern strings that are matched against all source file paths before transformation. If the file path matches **any** of the patterns, it will not be transformed. - -Providing regexp patterns that overlap with each other may result in files not being transformed that you expected to be transformed. For example: - -```json -{ - "transformIgnorePatterns": ["/node_modules/(?!(foo|bar)/)", "/bar/"] -} -``` - -The first pattern will match (and therefore not transform) files inside `/node_modules` except for those in `/node_modules/foo/` and `/node_modules/bar/`. The second pattern will match (and therefore not transform) files inside any path with `/bar/` in it. With the two together, files in `/node_modules/bar/` will not be transformed because it does match the second pattern, even though it was excluded by the first. - -Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled code. Since all files inside `node_modules` are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use `transformIgnorePatterns` to allow transpiling such modules. You'll find a good example of this use case in [React Native Guide](/docs/tutorial-react-native#transformignorepatterns-customization). - -These pattern strings match against the full path. Use the `` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. - -Example: - -```json -{ - "transformIgnorePatterns": [ - "/bower_components/", - "/node_modules/" - ] -} -``` - -:::tip - -If you use `pnpm` and need to convert some packages under `node_modules`, you need to note that the packages in this folder (e.g. `node_modules/package-a/`) have been symlinked to the path under `.pnpm` (e.g. `node_modules/.pnpm/package-a@x.x.x/node_modules/package-a/`), so using `/node_modules/(?!(package-a|@scope/pkg-b)/)` directly will not be recognized, while is to use: - -```json -{ - "transformIgnorePatterns": [ - "/node_modules/.pnpm/(?!(package-a|@scope\\+pkg-b)@)" - ] -} -``` - -It should be noted that the folder name of pnpm under `.pnpm` is the package name plus `@` and version number, so writing `/` will not be recognized, but using `@` can. - -Also note that you need using '\`${path.join(\_\_dirname, '../..')}/node_modules/.pnpm/...\`' instead of `/node_modules/.pnpm/...` when the config file is under `~/packages/lib-a/`, or using relative pattern `node_modules/(?!.pnpm|package-a|@scope/pkg-b)` to match the second 'node_modules/' in 'node_modules/.pnpm/@scope+pkg-b@xxx/node_modules/@scope/pkg-b/' - -::: - -### `unmockedModulePathPatterns` \[array<string>] - -Default: `[]` - -An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them. If a module's path matches any of the patterns in this list, it will not be automatically mocked by the module loader. - -This is useful for some commonly used 'utility' modules that are almost always used as implementation details almost all the time (like `underscore`, `lodash`, etc). It's generally a best practice to keep this list as small as possible and always use explicit `jest.mock()`/`jest.unmock()` calls in individual tests. Explicit per-test setup is far easier for other readers of the test to reason about the environment the test will run in. - -It is possible to override this setting in individual tests by explicitly calling `jest.mock()` at the top of the test file. - -### `verbose` \[boolean] - -Default: `false` or `true` if there is only one test file to run - -Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. - -### `watchPathIgnorePatterns` \[array<string>] - -Default: `[]` - -An array of RegExp patterns that are matched against all source file paths before re-running tests in watch mode. If the file path matches any of the patterns, when it is updated, it will not trigger a re-run of tests. - -These patterns match against the full path. Use the `` string token to include the path to your project's root directory to prevent it from accidentally ignoring all of your files in different environments that may have different root directories. Example: `["/node_modules/"]`. - -Even if nothing is specified here, the watcher will ignore changes to any hidden files and directories, i.e. files and folders that begin with a dot (`.`). - -### `watchPlugins` \[array<string | \[string, Object]>] - -Default: `[]` - -This option allows you to use custom watch plugins. Read more about watch plugins [here](watch-plugins). - -Examples of watch plugins include: - -- [`jest-watch-master`](https://github.com/rickhanlonii/jest-watch-master) -- [`jest-watch-select-projects`](https://github.com/rogeliog/jest-watch-select-projects) -- [`jest-watch-suspend`](https://github.com/unional/jest-watch-suspend) -- [`jest-watch-typeahead`](https://github.com/jest-community/jest-watch-typeahead) -- [`jest-watch-yarn-workspaces`](https://github.com/cameronhunter/jest-watch-directories/tree/master/packages/jest-watch-yarn-workspaces) - -:::info - -The values in the `watchPlugins` property value can omit the `jest-watch-` prefix of the package name. - -::: - -### `watchman` \[boolean] - -Default: `true` - -Whether to use [`watchman`](https://facebook.github.io/watchman/) for file crawling. - -### `//` \[string] - -No default - -This option allows comments in `package.json`. Include the comment text as the value of this key anywhere in `package.json`. - -Example: - -```json -{ - "name": "my-project", - "jest": { - "//": "Comment goes here", - "verbose": true - } -} -``` diff --git a/website/versioned_docs/version-25.x/DynamoDB.md b/website/versioned_docs/version-25.x/DynamoDB.md deleted file mode 100644 index a5abd9147aed..000000000000 --- a/website/versioned_docs/version-25.x/DynamoDB.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -id: dynamodb -title: Using with DynamoDB ---- - -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [DynamoDB](https://aws.amazon.com/dynamodb/). - -## Use jest-dynamodb Preset - -[Jest DynamoDB](https://github.com/shelfio/jest-dynamodb) provides all required configuration to run your tests using DynamoDB. - -1. First, install `@shelf/jest-dynamodb` - -``` -yarn add @shelf/jest-dynamodb --dev -``` - -2. Specify preset in your Jest configuration: - -```json -{ - "preset": "@shelf/jest-dynamodb" -} -``` - -3. Create `jest-dynamodb-config.js` and define DynamoDB tables - -See [Create Table API](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#createTable-property) - -```js -module.exports = { - tables: [ - { - TableName: `files`, - KeySchema: [{AttributeName: 'id', KeyType: 'HASH'}], - AttributeDefinitions: [{AttributeName: 'id', AttributeType: 'S'}], - ProvisionedThroughput: {ReadCapacityUnits: 1, WriteCapacityUnits: 1}, - }, - // etc - ], -}; -``` - -4. Configure DynamoDB client - -```js -const {DocumentClient} = require('aws-sdk/clients/dynamodb'); - -const isTest = process.env.JEST_WORKER_ID; -const config = { - convertEmptyValues: true, - ...(isTest && { - endpoint: 'localhost:8000', - sslEnabled: false, - region: 'local-env', - }), -}; - -const ddb = new DocumentClient(config); -``` - -5. Write tests - -```js -it('should insert item into table', async () => { - await ddb - .put({TableName: 'files', Item: {id: '1', hello: 'world'}}) - .promise(); - - const {Item} = await ddb.get({TableName: 'files', Key: {id: '1'}}).promise(); - - expect(Item).toEqual({ - id: '1', - hello: 'world', - }); -}); -``` - -There's no need to load any dependencies. - -See [documentation](https://github.com/shelfio/jest-dynamodb) for details. diff --git a/website/versioned_docs/version-25.x/ECMAScriptModules.md b/website/versioned_docs/version-25.x/ECMAScriptModules.md deleted file mode 100644 index 61f7fbbbff8a..000000000000 --- a/website/versioned_docs/version-25.x/ECMAScriptModules.md +++ /dev/null @@ -1,75 +0,0 @@ ---- -id: ecmascript-modules -title: ECMAScript Modules ---- - -:::caution - -Jest ships with **experimental** support for ECMAScript Modules (ESM). - -The implementation may have bugs and lack features. For the latest status check out the [issue](https://github.com/jestjs/jest/issues/9430) and the [label](https://github.com/jestjs/jest/labels/ES%20Modules) on the issue tracker. - -Also note that the APIs Jest uses to implement ESM support are still [considered experimental by Node](https://nodejs.org/api/vm.html#vm_class_vm_module) (as of version `18.8.0`). - -::: - -With the warnings out of the way, this is how you activate ESM support in your tests. - -1. Ensure you either disable [code transforms](Configuration.md#transform-objectstring-pathtotransformer--pathtotransformer-object) by passing `transform: {}` or otherwise configure your transformer to emit ESM rather than the default CommonJS (CJS). -1. Execute `node` with `--experimental-vm-modules`, e.g. `node --experimental-vm-modules node_modules/jest/bin/jest.js` or `NODE_OPTIONS=--experimental-vm-modules npx jest` etc. - - On Windows, you can use [`cross-env`](https://github.com/kentcdodds/cross-env) to be able to set environment variables. - - If you use Yarn, you can use `yarn node --experimental-vm-modules $(yarn bin jest)`. This command will also work if you use [Yarn Plug'n'Play](https://yarnpkg.com/features/pnp). - -1. Beyond that, we attempt to follow `node`'s logic for activating "ESM mode" (such as looking at `type` in `package.json` or `mjs` files), see [their docs](https://nodejs.org/api/esm.html#esm_enabling) for details - -## Differences between ESM and CommonJS - -Most of the differences are explained in [Node's documentation](https://nodejs.org/api/esm.html#esm_differences_between_es_modules_and_commonjs), but in addition to the things mentioned there, Jest injects a special variable into all executed files - the [`jest` object](JestObjectAPI.md). To access this object in ESM, you need to import it from the `@jest/globals` module. - -```js -import {jest} from '@jest/globals'; - -jest.useFakeTimers(); - -// etc. -``` - -Additionally, since ESM evaluates static `import` statements before looking at the code, the hoisting of `jest.mock` calls that happens in CJS won't work in ESM. To mock modules in ESM, you need to use `require` or dynamic `import()` after `jest.mock` calls to load the mocked modules - the same applies to modules which load the mocked modules. - -```js title="main.cjs" -const {BrowserWindow, app} = require('electron'); - -// etc. - -module.exports = {example}; -``` - -```js title="main.test.cjs" -import {createRequire} from 'node:module'; -import {jest} from '@jest/globals'; - -const require = createRequire(import.meta.url); - -jest.mock('electron', () => ({ - app: { - on: jest.fn(), - whenReady: jest.fn(() => Promise.resolve()), - }, - BrowserWindow: jest.fn().mockImplementation(() => ({ - // partial mocks. - })), -})); - -const {BrowserWindow} = require('electron'); -const exported = require('./main.cjs'); - -// alternatively -const {BrowserWindow} = (await import('electron')).default; -const exported = await import('./main.cjs'); - -// etc. -``` - -Please note that we currently don't support `jest.mock` in a clean way in ESM, but that is something we intend to add proper support for in the future. Follow [this issue](https://github.com/jestjs/jest/issues/10025) for updates. diff --git a/website/versioned_docs/version-25.x/EnvironmentVariables.md b/website/versioned_docs/version-25.x/EnvironmentVariables.md deleted file mode 100644 index fb50c3e72d08..000000000000 --- a/website/versioned_docs/version-25.x/EnvironmentVariables.md +++ /dev/null @@ -1,14 +0,0 @@ ---- -id: environment-variables -title: Environment Variables ---- - -Jest sets the following environment variables: - -### `NODE_ENV` - -Set to `'test'` if it's not already set to something else. - -### `JEST_WORKER_ID` - -Each worker process is assigned a unique id (index-based that starts with `1`). This is set to `1` for all tests when [`runInBand`](CLI.md#--runinband) is set to true. diff --git a/website/versioned_docs/version-25.x/Es6ClassMocks.md b/website/versioned_docs/version-25.x/Es6ClassMocks.md deleted file mode 100644 index f4e864e5eca3..000000000000 --- a/website/versioned_docs/version-25.x/Es6ClassMocks.md +++ /dev/null @@ -1,448 +0,0 @@ ---- -id: es6-class-mocks -title: ES6 Class Mocks ---- - -Jest can be used to mock ES6 classes that are imported into files you want to test. - -ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using [mock functions](MockFunctions.md). - -## An ES6 Class Example - -We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. - -```javascript title="sound-player.js" -export default class SoundPlayer { - constructor() { - this.foo = 'bar'; - } - - playSoundFile(fileName) { - console.log('Playing sound file ' + fileName); - } -} -``` - -```javascript title="sound-player-consumer.js" -import SoundPlayer from './sound-player'; - -export default class SoundPlayerConsumer { - constructor() { - this.soundPlayer = new SoundPlayer(); - } - - playSomethingCool() { - const coolSoundFileName = 'song.mp3'; - this.soundPlayer.playSoundFile(coolSoundFileName); - } -} -``` - -## The 4 ways to create an ES6 class mock - -### Automatic mock - -Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with [mock functions](MockFunctions.md) that always return `undefined`. Method calls are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. - -:::note - -If you use arrow functions in your classes, they will _not_ be part of the mock. The reason for that is that arrow functions are not present on the object's prototype, they are merely properties holding a reference to a function. - -::: - -If you don't need to replace the implementation of the class, this is the easiest option to set up. For example: - -```javascript -import SoundPlayer from './sound-player'; -import SoundPlayerConsumer from './sound-player-consumer'; -jest.mock('./sound-player'); // SoundPlayer is now a mock constructor - -beforeEach(() => { - // Clear all instances and calls to constructor and all methods: - SoundPlayer.mockClear(); -}); - -it('We can check if the consumer called the class constructor', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - expect(SoundPlayer).toHaveBeenCalledTimes(1); -}); - -it('We can check if the consumer called a method on the class instance', () => { - // Show that mockClear() is working: - expect(SoundPlayer).not.toHaveBeenCalled(); - - const soundPlayerConsumer = new SoundPlayerConsumer(); - // Constructor should have been called again: - expect(SoundPlayer).toHaveBeenCalledTimes(1); - - const coolSoundFileName = 'song.mp3'; - soundPlayerConsumer.playSomethingCool(); - - // mock.instances is available with automatic mocks: - const mockSoundPlayerInstance = SoundPlayer.mock.instances[0]; - const mockPlaySoundFile = mockSoundPlayerInstance.playSoundFile; - expect(mockPlaySoundFile.mock.calls[0][0]).toBe(coolSoundFileName); - // Equivalent to above check: - expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName); - expect(mockPlaySoundFile).toHaveBeenCalledTimes(1); -}); -``` - -### Manual mock - -Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. - -```javascript title="__mocks__/sound-player.js" -// Import this named export into your test file: -export const mockPlaySoundFile = jest.fn(); -const mock = jest.fn().mockImplementation(() => { - return {playSoundFile: mockPlaySoundFile}; -}); - -export default mock; -``` - -Import the mock and the mock method shared by all instances: - -```javascript title="sound-player-consumer.test.js" -import SoundPlayer, {mockPlaySoundFile} from './sound-player'; -import SoundPlayerConsumer from './sound-player-consumer'; -jest.mock('./sound-player'); // SoundPlayer is now a mock constructor - -beforeEach(() => { - // Clear all instances and calls to constructor and all methods: - SoundPlayer.mockClear(); - mockPlaySoundFile.mockClear(); -}); - -it('We can check if the consumer called the class constructor', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - expect(SoundPlayer).toHaveBeenCalledTimes(1); -}); - -it('We can check if the consumer called a method on the class instance', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - const coolSoundFileName = 'song.mp3'; - soundPlayerConsumer.playSomethingCool(); - expect(mockPlaySoundFile).toHaveBeenCalledWith(coolSoundFileName); -}); -``` - -### Calling [`jest.mock()`](JestObjectAPI.md#jestmockmodulename-factory-options) with the module factory parameter - -`jest.mock(path, moduleFactory)` takes a **module factory** argument. A module factory is a function that returns the mock. - -In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). - -```javascript -import SoundPlayer from './sound-player'; -const mockPlaySoundFile = jest.fn(); -jest.mock('./sound-player', () => { - return jest.fn().mockImplementation(() => { - return {playSoundFile: mockPlaySoundFile}; - }); -}); -``` - -:::caution - -Since calls to `jest.mock()` are hoisted to the top of the file, Jest prevents access to out-of-scope variables. By default, you cannot first define a variable and then use it in the factory. Jest will disable this check for variables that start with the word `mock`. However, it is still up to you to guarantee that they will be initialized on time. Be aware of [Temporal Dead Zone](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz). - -::: - -For example, the following will throw an out-of-scope error due to the use of `fake` instead of `mock` in the variable declaration. - -```javascript -// Note: this will fail -import SoundPlayer from './sound-player'; -const fakePlaySoundFile = jest.fn(); -jest.mock('./sound-player', () => { - return jest.fn().mockImplementation(() => { - return {playSoundFile: fakePlaySoundFile}; - }); -}); -``` - -The following will throw a `ReferenceError` despite using `mock` in the variable declaration, as the `mockSoundPlayer` is not wrapped in an arrow function and thus accessed before initialization after hoisting. - -```javascript -import SoundPlayer from './sound-player'; -const mockSoundPlayer = jest.fn().mockImplementation(() => { - return {playSoundFile: mockPlaySoundFile}; -}); -// results in a ReferenceError -jest.mock('./sound-player', () => { - return mockSoundPlayer; -}); -``` - -### Replacing the mock using [`mockImplementation()`](MockFunctionAPI.md#mockfnmockimplementationfn) or [`mockImplementationOnce()`](MockFunctionAPI.md#mockfnmockimplementationoncefn) - -You can replace all of the above mocks in order to change the implementation, for a single test or all tests, by calling `mockImplementation()` on the existing mock. - -Calls to jest.mock are hoisted to the top of the code. You can specify a mock later, e.g. in `beforeAll()`, by calling `mockImplementation()` (or `mockImplementationOnce()`) on the existing mock instead of using the factory parameter. This also allows you to change the mock between tests, if needed: - -```javascript -import SoundPlayer from './sound-player'; -import SoundPlayerConsumer from './sound-player-consumer'; - -jest.mock('./sound-player'); - -describe('When SoundPlayer throws an error', () => { - beforeAll(() => { - SoundPlayer.mockImplementation(() => { - return { - playSoundFile: () => { - throw new Error('Test error'); - }, - }; - }); - }); - - it('Should throw an error when calling playSomethingCool', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - expect(() => soundPlayerConsumer.playSomethingCool()).toThrow(); - }); -}); -``` - -## In depth: Understanding mock constructor functions - -Building your constructor function mock using `jest.fn().mockImplementation()` makes mocks appear more complicated than they really are. This section shows how you can create your own mocks to illustrate how mocking works. - -### Manual mock that is another ES6 class - -If you define an ES6 class using the same filename as the mocked class in the `__mocks__` folder, it will serve as the mock. This class will be used in place of the real class. This allows you to inject a test implementation for the class, but does not provide a way to spy on calls. - -For the contrived example, the mock might look like this: - -```javascript title="__mocks__/sound-player.js" -export default class SoundPlayer { - constructor() { - console.log('Mock SoundPlayer: constructor was called'); - } - - playSoundFile() { - console.log('Mock SoundPlayer: playSoundFile was called'); - } -} -``` - -### Mock using module factory parameter - -The module factory function passed to `jest.mock(path, moduleFactory)` can be a HOF that returns a function\*. This will allow calling `new` on the mock. Again, this allows you to inject different behavior for testing, but does not provide a way to spy on calls. - -#### \* Module factory function must return a function - -In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). - -```javascript -jest.mock('./sound-player', () => { - return function () { - return {playSoundFile: () => {}}; - }; -}); -``` - -:::note - -The mock can't be an arrow function because calling `new` on an arrow function is not allowed in JavaScript. So this won't work: - -```javascript -jest.mock('./sound-player', () => { - return () => { - // Does not work; arrow functions can't be called with new - return {playSoundFile: () => {}}; - }; -}); -``` - -This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, unless the code is transpiled to ES5, e.g. by `@babel/preset-env`. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.) - -::: - -## Mocking a specific method of a class - -Lets say that you want to mock or spy on the method `playSoundFile` within the class `SoundPlayer`. A simple example: - -```javascript -// your jest test file below -import SoundPlayer from './sound-player'; -import SoundPlayerConsumer from './sound-player-consumer'; - -const playSoundFileMock = jest - .spyOn(SoundPlayer.prototype, 'playSoundFile') - .mockImplementation(() => { - console.log('mocked function'); - }); // comment this line if just want to "spy" - -it('player consumer plays music', () => { - const player = new SoundPlayerConsumer(); - player.playSomethingCool(); - expect(playSoundFileMock).toHaveBeenCalled(); -}); -``` - -### Static, getter and setter methods - -Lets imagine our class `SoundPlayer` has a getter method `foo` and a static method `brand` - -```javascript -export default class SoundPlayer { - constructor() { - this.foo = 'bar'; - } - - playSoundFile(fileName) { - console.log('Playing sound file ' + fileName); - } - - get foo() { - return 'bar'; - } - static brand() { - return 'player-brand'; - } -} -``` - -You can mock/spy on them easily, here is an example: - -```javascript -// your jest test file below -import SoundPlayer from './sound-player'; - -const staticMethodMock = jest - .spyOn(SoundPlayer, 'brand') - .mockImplementation(() => 'some-mocked-brand'); - -const getterMethodMock = jest - .spyOn(SoundPlayer.prototype, 'foo', 'get') - .mockImplementation(() => 'some-mocked-result'); - -it('custom methods are called', () => { - const player = new SoundPlayer(); - const foo = player.foo; - const brand = SoundPlayer.brand(); - - expect(staticMethodMock).toHaveBeenCalled(); - expect(getterMethodMock).toHaveBeenCalled(); -}); -``` - -## Keeping track of usage (spying on the mock) - -Injecting a test implementation is helpful, but you will probably also want to test whether the class constructor and methods are called with the correct parameters. - -### Spying on the constructor - -In order to track calls to the constructor, replace the function returned by the HOF with a Jest mock function. Create it with [`jest.fn()`](JestObjectAPI.md#jestfnimplementation), and then specify its implementation with `mockImplementation()`. - -```javascript -import SoundPlayer from './sound-player'; -jest.mock('./sound-player', () => { - // Works and lets you check for constructor calls: - return jest.fn().mockImplementation(() => { - return {playSoundFile: () => {}}; - }); -}); -``` - -This will let us inspect usage of our mocked class, using `SoundPlayer.mock.calls`: `expect(SoundPlayer).toHaveBeenCalled();` or near-equivalent: `expect(SoundPlayer.mock.calls.length).toBeGreaterThan(0);` - -### Mocking non-default class exports - -If the class is **not** the default export from the module then you need to return an object with the key that is the same as the class export name. - -```javascript -import {SoundPlayer} from './sound-player'; -jest.mock('./sound-player', () => { - // Works and lets you check for constructor calls: - return { - SoundPlayer: jest.fn().mockImplementation(() => { - return {playSoundFile: () => {}}; - }), - }; -}); -``` - -### Spying on methods of our class - -Our mocked class will need to provide any member functions (`playSoundFile` in the example) that will be called during our tests, or else we'll get an error for calling a function that doesn't exist. But we'll probably want to also spy on calls to those methods, to ensure that they were called with the expected parameters. - -A new object will be created each time the mock constructor function is called during tests. To spy on method calls in all of these objects, we populate `playSoundFile` with another mock function, and store a reference to that same mock function in our test file, so it's available during tests. - -```javascript -import SoundPlayer from './sound-player'; -const mockPlaySoundFile = jest.fn(); -jest.mock('./sound-player', () => { - return jest.fn().mockImplementation(() => { - return {playSoundFile: mockPlaySoundFile}; - // Now we can track calls to playSoundFile - }); -}); -``` - -The manual mock equivalent of this would be: - -```javascript title="__mocks__/sound-player.js" -// Import this named export into your test file -export const mockPlaySoundFile = jest.fn(); -const mock = jest.fn().mockImplementation(() => { - return {playSoundFile: mockPlaySoundFile}; -}); - -export default mock; -``` - -Usage is similar to the module factory function, except that you can omit the second argument from `jest.mock()`, and you must import the mocked method into your test file, since it is no longer defined there. Use the original module path for this; don't include `__mocks__`. - -### Cleaning up between tests - -To clear the record of calls to the mock constructor function and its methods, we call [`mockClear()`](MockFunctionAPI.md#mockfnmockclear) in the `beforeEach()` function: - -```javascript -beforeEach(() => { - SoundPlayer.mockClear(); - mockPlaySoundFile.mockClear(); -}); -``` - -## Complete example - -Here's a complete test file which uses the module factory parameter to `jest.mock`: - -```javascript title="sound-player-consumer.test.js" -import SoundPlayer from './sound-player'; -import SoundPlayerConsumer from './sound-player-consumer'; - -const mockPlaySoundFile = jest.fn(); -jest.mock('./sound-player', () => { - return jest.fn().mockImplementation(() => { - return {playSoundFile: mockPlaySoundFile}; - }); -}); - -beforeEach(() => { - SoundPlayer.mockClear(); - mockPlaySoundFile.mockClear(); -}); - -it('The consumer should be able to call new() on SoundPlayer', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - // Ensure constructor created the object: - expect(soundPlayerConsumer).toBeTruthy(); -}); - -it('We can check if the consumer called the class constructor', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - expect(SoundPlayer).toHaveBeenCalledTimes(1); -}); - -it('We can check if the consumer called a method on the class instance', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - const coolSoundFileName = 'song.mp3'; - soundPlayerConsumer.playSomethingCool(); - expect(mockPlaySoundFile.mock.calls[0][0]).toBe(coolSoundFileName); -}); -``` diff --git a/website/versioned_docs/version-25.x/ExpectAPI.md b/website/versioned_docs/version-25.x/ExpectAPI.md deleted file mode 100644 index f4432aa4d876..000000000000 --- a/website/versioned_docs/version-25.x/ExpectAPI.md +++ /dev/null @@ -1,1451 +0,0 @@ ---- -id: expect -title: Expect ---- - -When you're writing tests, you often need to check that values meet certain conditions. `expect` gives you access to a number of "matchers" that let you validate different things. - -:::tip - -For additional Jest matchers maintained by the Jest Community check out [`jest-extended`](https://github.com/jest-community/jest-extended). - -::: - -## Methods - -import TOCInline from '@theme/TOCInline'; - - - ---- - -## Reference - -### `expect(value)` - -The `expect` function is used every time you want to test a value. You will rarely call `expect` by itself. Instead, you will use `expect` along with a "matcher" function to assert something about a value. - -It's easier to understand this with an example. Let's say you have a method `bestLaCroixFlavor()` which is supposed to return the string `'grapefruit'`. Here's how you would test that: - -```js -test('the best flavor is grapefruit', () => { - expect(bestLaCroixFlavor()).toBe('grapefruit'); -}); -``` - -In this case, `toBe` is the matcher function. There are a lot of different matcher functions, documented below, to help you test different things. - -The argument to `expect` should be the value that your code produces, and any argument to the matcher should be the correct value. If you mix them up, your tests will still work, but the error messages on failing tests will look strange. - -### `expect.extend(matchers)` - -You can use `expect.extend` to add your own matchers to Jest. For example, let's say that you're testing a number utility library and you're frequently asserting that numbers appear within particular ranges of other numbers. You could abstract that into a `toBeWithinRange` matcher: - -```js -expect.extend({ - toBeWithinRange(received, floor, ceiling) { - const pass = received >= floor && received <= ceiling; - if (pass) { - return { - message: () => - `expected ${received} not to be within range ${floor} - ${ceiling}`, - pass: true, - }; - } else { - return { - message: () => - `expected ${received} to be within range ${floor} - ${ceiling}`, - pass: false, - }; - } - }, -}); - -test('numeric ranges', () => { - expect(100).toBeWithinRange(90, 110); - expect(101).not.toBeWithinRange(0, 100); - expect({apples: 6, bananas: 3}).toEqual({ - apples: expect.toBeWithinRange(1, 10), - bananas: expect.not.toBeWithinRange(11, 20), - }); -}); -``` - -:::info - -In TypeScript, when using `@types/jest` for example, you can declare the new `toBeWithinRange` matcher in the imported module like this: - -```ts -expect.extend({ - toBeWithinRange(received, floor, ceiling) { - // ... - }, -}); - -interface CustomMatchers { - toBeWithinRange(floor: number, ceiling: number): R; -} - -declare global { - namespace jest { - interface Expect extends CustomMatchers {} - interface Matchers extends CustomMatchers {} - interface InverseAsymmetricMatchers extends CustomMatchers {} - } -} -``` - -If you want to move the typings to a separate file (e.g. `types/jest/index.d.ts`), you may need to an export, e.g.: - -```ts -declare global { - namespace jest { - interface Matchers { - toBeWithinRange(a: number, b: number): R; - } - } -} -export {}; -``` - -::: - -#### Async Matchers - -`expect.extend` also supports async matchers. Async matchers return a Promise so you will need to await the returned value. Let's use an example matcher to illustrate the usage of them. We are going to implement a matcher called `toBeDivisibleByExternalValue`, where the divisible number is going to be pulled from an external source. - -```js -expect.extend({ - async toBeDivisibleByExternalValue(received) { - const externalValue = await getExternalValueFromRemoteSource(); - const pass = received % externalValue == 0; - if (pass) { - return { - message: () => - `expected ${received} not to be divisible by ${externalValue}`, - pass: true, - }; - } else { - return { - message: () => - `expected ${received} to be divisible by ${externalValue}`, - pass: false, - }; - } - }, -}); - -test('is divisible by external value', async () => { - await expect(100).toBeDivisibleByExternalValue(); - await expect(101).not.toBeDivisibleByExternalValue(); -}); -``` - -#### Custom Matchers API - -Matchers should return an object (or a Promise of an object) with two keys. `pass` indicates whether there was a match or not, and `message` provides a function with no arguments that returns an error message in case of failure. Thus, when `pass` is false, `message` should return the error message for when `expect(x).yourMatcher()` fails. And when `pass` is true, `message` should return the error message for when `expect(x).not.yourMatcher()` fails. - -Matchers are called with the argument passed to `expect(x)` followed by the arguments passed to `.yourMatcher(y, z)`: - -```js -expect.extend({ - yourMatcher(x, y, z) { - return { - pass: true, - message: () => '', - }; - }, -}); -``` - -These helper functions and properties can be found on `this` inside a custom matcher: - -#### `this.isNot` - -A boolean to let you know this matcher was called with the negated `.not` modifier allowing you to display a clear and correct matcher hint (see example code). - -#### `this.promise` - -A string allowing you to display a clear and correct matcher hint: - -- `'rejects'` if matcher was called with the promise `.rejects` modifier -- `'resolves'` if matcher was called with the promise `.resolves` modifier -- `''` if matcher was not called with a promise modifier - -#### `this.equals(a, b)` - -This is a deep-equality function that will return `true` if two objects have the same values (recursively). - -#### `this.expand` - -A boolean to let you know this matcher was called with an `expand` option. When Jest is called with the `--expand` flag, `this.expand` can be used to determine if Jest is expected to show full diffs and errors. - -#### `this.utils` - -There are a number of helpful tools exposed on `this.utils` primarily consisting of the exports from [`jest-matcher-utils`](https://github.com/jestjs/jest/tree/main/packages/jest-matcher-utils). - -The most useful ones are `matcherHint`, `printExpected` and `printReceived` to format the error messages nicely. For example, take a look at the implementation for the `toBe` matcher: - -```js -const diff = require('jest-diff'); -expect.extend({ - toBe(received, expected) { - const options = { - comment: 'Object.is equality', - isNot: this.isNot, - promise: this.promise, - }; - - const pass = Object.is(received, expected); - - const message = pass - ? () => - // eslint-disable-next-line prefer-template - this.utils.matcherHint('toBe', undefined, undefined, options) + - '\n\n' + - `Expected: not ${this.utils.printExpected(expected)}\n` + - `Received: ${this.utils.printReceived(received)}` - : () => { - const diffString = diff(expected, received, { - expand: this.expand, - }); - return ( - // eslint-disable-next-line prefer-template - this.utils.matcherHint('toBe', undefined, undefined, options) + - '\n\n' + - (diffString && diffString.includes('- Expect') - ? `Difference:\n\n${diffString}` - : `Expected: ${this.utils.printExpected(expected)}\n` + - `Received: ${this.utils.printReceived(received)}`) - ); - }; - - return {actual: received, message, pass}; - }, -}); -``` - -This will print something like this: - -```bash - expect(received).toBe(expected) - - Expected value to be (using Object.is): - "banana" - Received: - "apple" -``` - -When an assertion fails, the error message should give as much signal as necessary to the user so they can resolve their issue quickly. You should craft a precise failure message to make sure users of your custom assertions have a good developer experience. - -#### Custom snapshot matchers - -To use snapshot testing inside of your custom matcher you can import `jest-snapshot` and use it from within your matcher. - -Here's a snapshot matcher that trims a string to store for a given length, `.toMatchTrimmedSnapshot(length)`: - -```js -const {toMatchSnapshot} = require('jest-snapshot'); - -expect.extend({ - toMatchTrimmedSnapshot(received, length) { - return toMatchSnapshot.call( - this, - received.substring(0, length), - 'toMatchTrimmedSnapshot', - ); - }, -}); - -it('stores only 10 characters', () => { - expect('extra long string oh my gerd').toMatchTrimmedSnapshot(10); -}); - -/* -Stored snapshot will look like: - -exports[`stores only 10 characters: toMatchTrimmedSnapshot 1`] = `"extra long"`; -*/ -``` - -It's also possible to create custom matchers for inline snapshots, the snapshots will be correctly added to the custom matchers. However, inline snapshot will always try to append to the first argument or the second when the first argument is the property matcher, so it's not possible to accept custom arguments in the custom matchers. - -```js -const {toMatchInlineSnapshot} = require('jest-snapshot'); - -expect.extend({ - toMatchTrimmedInlineSnapshot(received, ...rest) { - return toMatchInlineSnapshot.call(this, received.substring(0, 10), ...rest); - }, -}); - -it('stores only 10 characters', () => { - expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot(); - /* - The snapshot will be added inline like - expect('extra long string oh my gerd').toMatchTrimmedInlineSnapshot( - `"extra long"` - ); - */ -}); -``` - -#### async - -If your custom inline snapshot matcher is async i.e. uses `async`-`await` you might encounter an error like "Multiple inline snapshots for the same call are not supported". Jest needs additional context information to find where the custom inline snapshot matcher was used to update the snapshots properly. - -```js -const {toMatchInlineSnapshot} = require('jest-snapshot'); - -expect.extend({ - async toMatchObservationInlineSnapshot(fn, ...rest) { - // The error (and its stacktrace) must be created before any `await` - this.error = new Error(); - - // The implementation of `observe` doesn't matter. - // It only matters that the custom snapshot matcher is async. - const observation = await observe(async () => { - await fn(); - }); - - return toMatchInlineSnapshot.call(this, recording, ...rest); - }, -}); - -it('observes something', async () => { - await expect(async () => { - return 'async action'; - }).toMatchTrimmedInlineSnapshot(); - /* - The snapshot will be added inline like - await expect(async () => { - return 'async action'; - }).toMatchTrimmedInlineSnapshot(`"async action"`); - */ -}); -``` - -#### Bail out - -Usually `jest` tries to match every snapshot that is expected in a test. - -Sometimes it might not make sense to continue the test if a prior snapshot failed. For example, when you make snapshots of a state-machine after various transitions you can abort the test once one transition produced the wrong state. - -In that case you can implement a custom snapshot matcher that throws on the first mismatch instead of collecting every mismatch. - -```js -const {toMatchInlineSnapshot} = require('jest-snapshot'); - -expect.extend({ - toMatchStateInlineSnapshot(...args) { - this.dontThrow = () => {}; - - return toMatchInlineSnapshot.call(this, ...args); - }, -}); - -let state = 'initial'; - -function transition() { - // Typo in the implementation should cause the test to fail - if (state === 'INITIAL') { - state = 'pending'; - } else if (state === 'pending') { - state = 'done'; - } -} - -it('transitions as expected', () => { - expect(state).toMatchStateInlineSnapshot(`"initial"`); - - transition(); - // Already produces a mismatch. No point in continuing the test. - expect(state).toMatchStateInlineSnapshot(`"loading"`); - - transition(); - expect(state).toMatchStateInlineSnapshot(`"done"`); -}); -``` - -### `expect.anything()` - -`expect.anything()` matches anything but `null` or `undefined`. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, if you want to check that a mock function is called with a non-null argument: - -```js -test('map calls its argument with a non-null argument', () => { - const mock = jest.fn(); - [1].map(x => mock(x)); - expect(mock).toHaveBeenCalledWith(expect.anything()); -}); -``` - -### `expect.any(constructor)` - -`expect.any(constructor)` matches anything that was created with the given constructor or if it's a primitive that is of the passed type. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, if you want to check that a mock function is called with a number: - -```js -class Cat {} -function getCat(fn) { - return fn(new Cat()); -} - -test('randocall calls its callback with a class instance', () => { - const mock = jest.fn(); - getCat(mock); - expect(mock).toHaveBeenCalledWith(expect.any(Cat)); -}); - -function randocall(fn) { - return fn(Math.floor(Math.random() * 6 + 1)); -} - -test('randocall calls its callback with a number', () => { - const mock = jest.fn(); - randocall(mock); - expect(mock).toHaveBeenCalledWith(expect.any(Number)); -}); -``` - -### `expect.arrayContaining(array)` - -`expect.arrayContaining(array)` matches a received array which contains all of the elements in the expected array. That is, the expected array is a **subset** of the received array. Therefore, it matches a received array which contains elements that are **not** in the expected array. - -You can use it instead of a literal value: - -- in `toEqual` or `toBeCalledWith` -- to match a property in `objectContaining` or `toMatchObject` - -```js -describe('arrayContaining', () => { - const expected = ['Alice', 'Bob']; - it('matches even if received contains additional elements', () => { - expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected)); - }); - it('does not match if received does not contain expected elements', () => { - expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected)); - }); -}); -``` - -```js -describe('Beware of a misunderstanding! A sequence of dice rolls', () => { - const expected = [1, 2, 3, 4, 5, 6]; - it('matches even with an unexpected number 7', () => { - expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual( - expect.arrayContaining(expected), - ); - }); - it('does not match without an expected number 2', () => { - expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual( - expect.arrayContaining(expected), - ); - }); -}); -``` - -### `expect.assertions(number)` - -`expect.assertions(number)` verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. - -For example, let's say that we have a function `doAsync` that receives two callbacks `callback1` and `callback2`, it will asynchronously call both of them in an unknown order. We can test this with: - -```js -test('doAsync calls both callbacks', () => { - expect.assertions(2); - function callback1(data) { - expect(data).toBeTruthy(); - } - function callback2(data) { - expect(data).toBeTruthy(); - } - - doAsync(callback1, callback2); -}); -``` - -The `expect.assertions(2)` call ensures that both callbacks actually get called. - -### `expect.hasAssertions()` - -`expect.hasAssertions()` verifies that at least one assertion is called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called. - -For example, let's say that we have a few functions that all deal with state. `prepareState` calls a callback with a state object, `validateState` runs on that state object, and `waitOnState` returns a promise that waits until all `prepareState` callbacks complete. We can test this with: - -```js -test('prepareState prepares a valid state', () => { - expect.hasAssertions(); - prepareState(state => { - expect(validateState(state)).toBeTruthy(); - }); - return waitOnState(); -}); -``` - -The `expect.hasAssertions()` call ensures that the `prepareState` callback actually gets called. - -### `expect.not.arrayContaining(array)` - -`expect.not.arrayContaining(array)` matches a received array which does not contain all of the elements in the expected array. That is, the expected array **is not a subset** of the received array. - -It is the inverse of `expect.arrayContaining`. - -```js -describe('not.arrayContaining', () => { - const expected = ['Samantha']; - - it('matches if the actual array does not contain the expected elements', () => { - expect(['Alice', 'Bob', 'Eve']).toEqual( - expect.not.arrayContaining(expected), - ); - }); -}); -``` - -### `expect.not.objectContaining(object)` - -`expect.not.objectContaining(object)` matches any received object that does not recursively match the expected properties. That is, the expected object **is not a subset** of the received object. Therefore, it matches a received object which contains properties that are **not** in the expected object. - -It is the inverse of `expect.objectContaining`. - -```js -describe('not.objectContaining', () => { - const expected = {foo: 'bar'}; - - it('matches if the actual object does not contain expected key: value pairs', () => { - expect({bar: 'baz'}).toEqual(expect.not.objectContaining(expected)); - }); -}); -``` - -### `expect.not.stringContaining(string)` - -`expect.not.stringContaining(string)` matches the received value if it is not a string or if it is a string that does not contain the exact expected string. - -It is the inverse of `expect.stringContaining`. - -```js -describe('not.stringContaining', () => { - const expected = 'Hello world!'; - - it('matches if the received value does not contain the expected substring', () => { - expect('How are you?').toEqual(expect.not.stringContaining(expected)); - }); -}); -``` - -### `expect.not.stringMatching(string | regexp)` - -`expect.not.stringMatching(string | regexp)` matches the received value if it is not a string or if it is a string that does not match the expected string or regular expression. - -It is the inverse of `expect.stringMatching`. - -```js -describe('not.stringMatching', () => { - const expected = /Hello world!/; - - it('matches if the received value does not match the expected regex', () => { - expect('How are you?').toEqual(expect.not.stringMatching(expected)); - }); -}); -``` - -### `expect.objectContaining(object)` - -`expect.objectContaining(object)` matches any received object that recursively matches the expected properties. That is, the expected object is a **subset** of the received object. Therefore, it matches a received object which contains properties that **are present** in the expected object. - -Instead of literal property values in the expected object, you can use matchers, `expect.anything()`, and so on. - -For example, let's say that we expect an `onPress` function to be called with an `Event` object, and all we need to verify is that the event has `event.x` and `event.y` properties. We can do that with: - -```js -test('onPress gets called with the right thing', () => { - const onPress = jest.fn(); - simulatePresses(onPress); - expect(onPress).toHaveBeenCalledWith( - expect.objectContaining({ - x: expect.any(Number), - y: expect.any(Number), - }), - ); -}); -``` - -### `expect.stringContaining(string)` - -`expect.stringContaining(string)` matches the received value if it is a string that contains the exact expected string. - -### `expect.stringMatching(string | regexp)` - -`expect.stringMatching(string | regexp)` matches the received value if it is a string that matches the expected string or regular expression. - -You can use it instead of a literal value: - -- in `toEqual` or `toBeCalledWith` -- to match an element in `arrayContaining` -- to match a property in `objectContaining` or `toMatchObject` - -This example also shows how you can nest multiple asymmetric matchers, with `expect.stringMatching` inside the `expect.arrayContaining`. - -```js -describe('stringMatching in arrayContaining', () => { - const expected = [ - expect.stringMatching(/^Alic/), - expect.stringMatching(/^[BR]ob/), - ]; - it('matches even if received contains additional elements', () => { - expect(['Alicia', 'Roberto', 'Evelina']).toEqual( - expect.arrayContaining(expected), - ); - }); - it('does not match if received does not contain expected elements', () => { - expect(['Roberto', 'Evelina']).not.toEqual( - expect.arrayContaining(expected), - ); - }); -}); -``` - -### `expect.addSnapshotSerializer(serializer)` - -You can call `expect.addSnapshotSerializer` to add a module that formats application-specific data structures. - -For an individual test file, an added module precedes any modules from `snapshotSerializers` configuration, which precede the default snapshot serializers for built-in JavaScript types and for React elements. The last module added is the first module tested. - -```js -import serializer from 'my-serializer-module'; -expect.addSnapshotSerializer(serializer); - -// affects expect(value).toMatchSnapshot() assertions in the test file -``` - -If you add a snapshot serializer in individual test files instead of adding it to `snapshotSerializers` configuration: - -- You make the dependency explicit instead of implicit. -- You avoid limits to configuration that might cause you to eject from [create-react-app](https://github.com/facebookincubator/create-react-app). - -See [configuring Jest](Configuration.md#snapshotserializers-arraystring) for more information. - -### `.not` - -If you know how to test something, `.not` lets you test its opposite. For example, this code tests that the best La Croix flavor is not coconut: - -```js -test('the best flavor is not coconut', () => { - expect(bestLaCroixFlavor()).not.toBe('coconut'); -}); -``` - -### `.resolves` - -Use `resolves` to unwrap the value of a fulfilled promise so any other matcher can be chained. If the promise is rejected the assertion fails. - -For example, this code tests that the promise resolves and that the resulting value is `'lemon'`: - -```js -test('resolves to lemon', () => { - // make sure to add a return statement - return expect(Promise.resolve('lemon')).resolves.toBe('lemon'); -}); -``` - -:::note - -Since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. - -Alternatively, you can use `async/await` in combination with `.resolves`: - -```js -test('resolves to lemon', async () => { - await expect(Promise.resolve('lemon')).resolves.toBe('lemon'); - await expect(Promise.resolve('lemon')).resolves.not.toBe('octopus'); -}); -``` - -::: - -### `.rejects` - -Use `.rejects` to unwrap the reason of a rejected promise so any other matcher can be chained. If the promise is fulfilled the assertion fails. - -For example, this code tests that the promise rejects with reason `'octopus'`: - -```js -test('rejects to octopus', () => { - // make sure to add a return statement - return expect(Promise.reject(new Error('octopus'))).rejects.toThrow( - 'octopus', - ); -}); -``` - -:::note - -Since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. - -Alternatively, you can use `async/await` in combination with `.rejects`. - -```js -test('rejects to octopus', async () => { - await expect(Promise.reject(new Error('octopus'))).rejects.toThrow('octopus'); -}); -``` - -::: - -### `.toBe(value)` - -Use `.toBe` to compare primitive values or to check referential identity of object instances. It calls `Object.is` to compare values, which is even better for testing than `===` strict equality operator. - -For example, this code will validate some properties of the `can` object: - -```js -const can = { - name: 'pamplemousse', - ounces: 12, -}; - -describe('the can', () => { - test('has 12 ounces', () => { - expect(can.ounces).toBe(12); - }); - - test('has a sophisticated name', () => { - expect(can.name).toBe('pamplemousse'); - }); -}); -``` - -Don't use `.toBe` with floating-point numbers. For example, due to rounding, in JavaScript `0.2 + 0.1` is not strictly equal to `0.3`. If you have floating point numbers, try `.toBeCloseTo` instead. - -Although the `.toBe` matcher **checks** referential identity, it **reports** a deep comparison of values if the assertion fails. If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the `expect` function. For example, to assert whether or not elements are the same instance: - -- rewrite `expect(received).toBe(expected)` as `expect(Object.is(received, expected)).toBe(true)` -- rewrite `expect(received).not.toBe(expected)` as `expect(Object.is(received, expected)).toBe(false)` - -### `.toHaveBeenCalled()` - -Also under the alias: `.toBeCalled()` - -Use `.toHaveBeenCalledWith` to ensure that a mock function was called with specific arguments. The arguments are checked with the same algorithm that `.toEqual` uses. - -For example, let's say you have a `drinkAll(drink, flavour)` function that takes a `drink` function and applies it to all available beverages. You might want to check that `drink` gets called for `'lemon'`, but not for `'octopus'`, because `'octopus'` flavour is really weird and why would anything be octopus-flavoured? You can do that with this test suite: - -```js -function drinkAll(callback, flavour) { - if (flavour !== 'octopus') { - callback(flavour); - } -} - -describe('drinkAll', () => { - test('drinks something lemon-flavoured', () => { - const drink = jest.fn(); - drinkAll(drink, 'lemon'); - expect(drink).toHaveBeenCalled(); - }); - - test('does not drink something octopus-flavoured', () => { - const drink = jest.fn(); - drinkAll(drink, 'octopus'); - expect(drink).not.toHaveBeenCalled(); - }); -}); -``` - -### `.toHaveBeenCalledTimes(number)` - -Also under the alias: `.toBeCalledTimes(number)` - -Use `.toHaveBeenCalledTimes` to ensure that a mock function got called exact number of times. - -For example, let's say you have a `drinkEach(drink, Array)` function that takes a `drink` function and applies it to array of passed beverages. You might want to check that drink function was called exact number of times. You can do that with this test suite: - -```js -test('drinkEach drinks each drink', () => { - const drink = jest.fn(); - drinkEach(drink, ['lemon', 'octopus']); - expect(drink).toHaveBeenCalledTimes(2); -}); -``` - -### `.toHaveBeenCalledWith(arg1, arg2, ...)` - -Also under the alias: `.toBeCalledWith()` - -Use `.toHaveBeenCalledWith` to ensure that a mock function was called with specific arguments. The arguments are checked with the same algorithm that `.toEqual` uses. - -For example, let's say that you can register a beverage with a `register` function, and `applyToAll(f)` should apply the function `f` to all registered beverages. To make sure this works, you could write: - -```js -test('registration applies correctly to orange La Croix', () => { - const beverage = new LaCroix('orange'); - register(beverage); - const f = jest.fn(); - applyToAll(f); - expect(f).toHaveBeenCalledWith(beverage); -}); -``` - -### `.toHaveBeenLastCalledWith(arg1, arg2, ...)` - -Also under the alias: `.lastCalledWith(arg1, arg2, ...)` - -If you have a mock function, you can use `.toHaveBeenLastCalledWith` to test what arguments it was last called with. For example, let's say you have a `applyToAllFlavors(f)` function that applies `f` to a bunch of flavors, and you want to ensure that when you call it, the last flavor it operates on is `'mango'`. You can write: - -```js -test('applying to all flavors does mango last', () => { - const drink = jest.fn(); - applyToAllFlavors(drink); - expect(drink).toHaveBeenLastCalledWith('mango'); -}); -``` - -### `.toHaveBeenNthCalledWith(nthCall, arg1, arg2, ....)` - -Also under the alias: `.nthCalledWith(nthCall, arg1, arg2, ...)` - -If you have a mock function, you can use `.toHaveBeenNthCalledWith` to test what arguments it was nth called with. For example, let's say you have a `drinkEach(drink, Array)` function that applies `f` to a bunch of flavors, and you want to ensure that when you call it, the first flavor it operates on is `'lemon'` and the second one is `'octopus'`. You can write: - -```js -test('drinkEach drinks each drink', () => { - const drink = jest.fn(); - drinkEach(drink, ['lemon', 'octopus']); - expect(drink).toHaveBeenNthCalledWith(1, 'lemon'); - expect(drink).toHaveBeenNthCalledWith(2, 'octopus'); -}); -``` - -:::note - -The nth argument must be positive integer starting from 1. - -::: - -### `.toHaveReturned()` - -Also under the alias: `.toReturn()` - -If you have a mock function, you can use `.toHaveReturned` to test that the mock function successfully returned (i.e., did not throw an error) at least one time. For example, let's say you have a mock `drink` that returns `true`. You can write: - -```js -test('drinks returns', () => { - const drink = jest.fn(() => true); - - drink(); - - expect(drink).toHaveReturned(); -}); -``` - -### `.toHaveReturnedTimes(number)` - -Also under the alias: `.toReturnTimes(number)` - -Use `.toHaveReturnedTimes` to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. Any calls to the mock function that throw an error are not counted toward the number of times the function returned. - -For example, let's say you have a mock `drink` that returns `true`. You can write: - -```js -test('drink returns twice', () => { - const drink = jest.fn(() => true); - - drink(); - drink(); - - expect(drink).toHaveReturnedTimes(2); -}); -``` - -### `.toHaveReturnedWith(value)` - -Also under the alias: `.toReturnWith(value)` - -Use `.toHaveReturnedWith` to ensure that a mock function returned a specific value. - -For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: - -```js -test('drink returns La Croix', () => { - const beverage = {name: 'La Croix'}; - const drink = jest.fn(beverage => beverage.name); - - drink(beverage); - - expect(drink).toHaveReturnedWith('La Croix'); -}); -``` - -### `.toHaveLastReturnedWith(value)` - -Also under the alias: `.lastReturnedWith(value)` - -Use `.toHaveLastReturnedWith` to test the specific value that a mock function last returned. If the last call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. - -For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: - -```js -test('drink returns La Croix (Orange) last', () => { - const beverage1 = {name: 'La Croix (Lemon)'}; - const beverage2 = {name: 'La Croix (Orange)'}; - const drink = jest.fn(beverage => beverage.name); - - drink(beverage1); - drink(beverage2); - - expect(drink).toHaveLastReturnedWith('La Croix (Orange)'); -}); -``` - -### `.toHaveNthReturnedWith(nthCall, value)` - -Also under the alias: `.nthReturnedWith(nthCall, value)` - -Use `.toHaveNthReturnedWith` to test the specific value that a mock function returned for the nth call. If the nth call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. - -For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: - -```js -test('drink returns expected nth calls', () => { - const beverage1 = {name: 'La Croix (Lemon)'}; - const beverage2 = {name: 'La Croix (Orange)'}; - const drink = jest.fn(beverage => beverage.name); - - drink(beverage1); - drink(beverage2); - - expect(drink).toHaveNthReturnedWith(1, 'La Croix (Lemon)'); - expect(drink).toHaveNthReturnedWith(2, 'La Croix (Orange)'); -}); -``` - -:::note - -The nth argument must be positive integer starting from 1. - -::: - -### `.toHaveLength(number)` - -Use `.toHaveLength` to check that an object has a `.length` property and it is set to a certain numeric value. - -This is especially useful for checking arrays or strings size. - -```js -expect([1, 2, 3]).toHaveLength(3); -expect('abc').toHaveLength(3); -expect('').not.toHaveLength(5); -``` - -### `.toHaveProperty(keyPath, value?)` - -Use `.toHaveProperty` to check if property at provided reference `keyPath` exists for an object. For checking deeply nested properties in an object you may use [dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) or an array containing the keyPath for deep references. - -You can provide an optional `value` argument to compare the received property value (recursively for all properties of object instances, also known as deep equality, like the `toEqual` matcher). - -The following example contains a `houseForSale` object with nested properties. We are using `toHaveProperty` to check for the existence and values of various properties in the object. - -```js -// Object containing house features to be tested -const houseForSale = { - bath: true, - bedrooms: 4, - kitchen: { - amenities: ['oven', 'stove', 'washer'], - area: 20, - wallColor: 'white', - 'nice.oven': true, - }, - 'ceiling.height': 2, -}; - -test('this house has my desired features', () => { - // Example Referencing - expect(houseForSale).toHaveProperty('bath'); - expect(houseForSale).toHaveProperty('bedrooms', 4); - - expect(houseForSale).not.toHaveProperty('pool'); - - // Deep referencing using dot notation - expect(houseForSale).toHaveProperty('kitchen.area', 20); - expect(houseForSale).toHaveProperty('kitchen.amenities', [ - 'oven', - 'stove', - 'washer', - ]); - - expect(houseForSale).not.toHaveProperty('kitchen.open'); - - // Deep referencing using an array containing the keyPath - expect(houseForSale).toHaveProperty(['kitchen', 'area'], 20); - expect(houseForSale).toHaveProperty( - ['kitchen', 'amenities'], - ['oven', 'stove', 'washer'], - ); - expect(houseForSale).toHaveProperty(['kitchen', 'amenities', 0], 'oven'); - expect(houseForSale).toHaveProperty(['kitchen', 'nice.oven']); - expect(houseForSale).not.toHaveProperty(['kitchen', 'open']); - - // Referencing keys with dot in the key itself - expect(houseForSale).toHaveProperty(['ceiling.height'], 'tall'); -}); -``` - -### `.toBeCloseTo(number, numDigits?)` - -Use `toBeCloseTo` to compare floating point numbers for approximate equality. - -The optional `numDigits` argument limits the number of digits to check **after** the decimal point. For the default value `2`, the test criterion is `Math.abs(expected - received) < 0.005` (that is, `10 ** -2 / 2`). - -Intuitive equality comparisons often fail, because arithmetic on decimal (base 10) values often have rounding errors in limited precision binary (base 2) representation. For example, this test fails: - -```js -test('adding works sanely with decimals', () => { - expect(0.2 + 0.1).toBe(0.3); // Fails! -}); -``` - -It fails because in JavaScript, `0.2 + 0.1` is actually `0.30000000000000004`. - -For example, this test passes with a precision of 5 digits: - -```js -test('adding works sanely with decimals', () => { - expect(0.2 + 0.1).toBeCloseTo(0.3, 5); -}); -``` - -Because floating point errors are the problem that `toBeCloseTo` solves, it does not support big integer values. - -### `.toBeDefined()` - -Use `.toBeDefined` to check that a variable is not undefined. For example, if you want to check that a function `fetchNewFlavorIdea()` returns _something_, you can write: - -```js -test('there is a new flavor idea', () => { - expect(fetchNewFlavorIdea()).toBeDefined(); -}); -``` - -You could write `expect(fetchNewFlavorIdea()).not.toBe(undefined)`, but it's better practice to avoid referring to `undefined` directly in your code. - -### `.toBeFalsy()` - -Use `.toBeFalsy` when you don't care what a value is and you want to ensure a value is false in a boolean context. For example, let's say you have some application code that looks like: - -```js -drinkSomeLaCroix(); -if (!getErrors()) { - drinkMoreLaCroix(); -} -``` - -You may not care what `getErrors` returns, specifically - it might return `false`, `null`, or `0`, and your code would still work. So if you want to test there are no errors after drinking some La Croix, you could write: - -```js -test('drinking La Croix does not lead to errors', () => { - drinkSomeLaCroix(); - expect(getErrors()).toBeFalsy(); -}); -``` - -In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. - -### `.toBeGreaterThan(number | bigint)` - -Use `toBeGreaterThan` to compare `received > expected` for number or big integer values. For example, test that `ouncesPerCan()` returns a value of more than 10 ounces: - -```js -test('ounces per can is more than 10', () => { - expect(ouncesPerCan()).toBeGreaterThan(10); -}); -``` - -### `.toBeGreaterThanOrEqual(number | bigint)` - -Use `toBeGreaterThanOrEqual` to compare `received >= expected` for number or big integer values. For example, test that `ouncesPerCan()` returns a value of at least 12 ounces: - -```js -test('ounces per can is at least 12', () => { - expect(ouncesPerCan()).toBeGreaterThanOrEqual(12); -}); -``` - -### `.toBeLessThan(number | bigint)` - -Use `toBeLessThan` to compare `received < expected` for number or big integer values. For example, test that `ouncesPerCan()` returns a value of less than 20 ounces: - -```js -test('ounces per can is less than 20', () => { - expect(ouncesPerCan()).toBeLessThan(20); -}); -``` - -### `.toBeLessThanOrEqual(number | bigint)` - -Use `toBeLessThanOrEqual` to compare `received <= expected` for number or big integer values. For example, test that `ouncesPerCan()` returns a value of at most 12 ounces: - -```js -test('ounces per can is at most 12', () => { - expect(ouncesPerCan()).toBeLessThanOrEqual(12); -}); -``` - -### `.toBeInstanceOf(Class)` - -Use `.toBeInstanceOf(Class)` to check that an object is an instance of a class. This matcher uses `instanceof` underneath. - -```js -class A {} - -expect(new A()).toBeInstanceOf(A); -expect(() => {}).toBeInstanceOf(Function); -expect(new A()).toBeInstanceOf(Function); // throws -``` - -### `.toBeNull()` - -`.toBeNull()` is the same as `.toBe(null)` but the error messages are a bit nicer. So use `.toBeNull()` when you want to check that something is null. - -```js -function bloop() { - return null; -} - -test('bloop returns null', () => { - expect(bloop()).toBeNull(); -}); -``` - -### `.toBeTruthy()` - -Use `.toBeTruthy` when you don't care what a value is and you want to ensure a value is true in a boolean context. For example, let's say you have some application code that looks like: - -```js -drinkSomeLaCroix(); -if (thirstInfo()) { - drinkMoreLaCroix(); -} -``` - -You may not care what `thirstInfo` returns, specifically - it might return `true` or a complex object, and your code would still work. So if you want to test that `thirstInfo` will be truthy after drinking some La Croix, you could write: - -```js -test('drinking La Croix leads to having thirst info', () => { - drinkSomeLaCroix(); - expect(thirstInfo()).toBeTruthy(); -}); -``` - -In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. - -### `.toBeUndefined()` - -Use `.toBeUndefined` to check that a variable is undefined. For example, if you want to check that a function `bestDrinkForFlavor(flavor)` returns `undefined` for the `'octopus'` flavor, because there is no good octopus-flavored drink: - -```js -test('the best drink for octopus flavor is undefined', () => { - expect(bestDrinkForFlavor('octopus')).toBeUndefined(); -}); -``` - -You could write `expect(bestDrinkForFlavor('octopus')).toBe(undefined)`, but it's better practice to avoid referring to `undefined` directly in your code. - -### `.toBeNaN()` - -Use `.toBeNaN` when checking a value is `NaN`. - -```js -test('passes when value is NaN', () => { - expect(NaN).toBeNaN(); - expect(1).not.toBeNaN(); -}); -``` - -### `.toContain(item)` - -Use `.toContain` when you want to check that an item is in an array. For testing the items in the array, this uses `===`, a strict equality check. `.toContain` can also check whether a string is a substring of another string. - -For example, if `getAllFlavors()` returns an array of flavors and you want to be sure that `lime` is in there, you can write: - -```js -test('the flavor list contains lime', () => { - expect(getAllFlavors()).toContain('lime'); -}); -``` - -This matcher also accepts others iterables such as strings, sets, node lists and HTML collections. - -### `.toContainEqual(item)` - -Use `.toContainEqual` when you want to check that an item with a specific structure and values is contained in an array. For testing the items in the array, this matcher recursively checks the equality of all fields, rather than checking for object identity. - -```js -describe('my beverage', () => { - test('is delicious and not sour', () => { - const myBeverage = {delicious: true, sour: false}; - expect(myBeverages()).toContainEqual(myBeverage); - }); -}); -``` - -### `.toEqual(value)` - -Use `.toEqual` to compare recursively all properties of object instances (also known as "deep" equality). It calls `Object.is` to compare primitive values, which is even better for testing than `===` strict equality operator. - -For example, `.toEqual` and `.toBe` behave differently in this test suite, so all the tests pass: - -```js -const can1 = { - flavor: 'grapefruit', - ounces: 12, -}; -const can2 = { - flavor: 'grapefruit', - ounces: 12, -}; - -describe('the La Croix cans on my desk', () => { - test('have all the same properties', () => { - expect(can1).toEqual(can2); - }); - test('are not the exact same can', () => { - expect(can1).not.toBe(can2); - }); -}); -``` - -:::tip - -`toEqual` ignores object keys with `undefined` properties, `undefined` array items, array sparseness, or object type mismatch. To take these into account use [`.toStrictEqual`](#tostrictequalvalue) instead. - -::: - -:::info - -`.toEqual` won't perform a _deep equality_ check for two errors. Only the `message` property of an Error is considered for equality. It is recommended to use the `.toThrow` matcher for testing against errors. - -::: - -If differences between properties do not help you to understand why a test fails, especially if the report is large, then you might move the comparison into the `expect` function. For example, use `equals` method of `Buffer` class to assert whether or not buffers contain the same content: - -- rewrite `expect(received).toEqual(expected)` as `expect(received.equals(expected)).toBe(true)` -- rewrite `expect(received).not.toEqual(expected)` as `expect(received.equals(expected)).toBe(false)` - -### `.toMatch(regexp | string)` - -Use `.toMatch` to check that a string matches a regular expression. - -For example, you might not know what exactly `essayOnTheBestFlavor()` returns, but you know it's a really long string, and the substring `grapefruit` should be in there somewhere. You can test this with: - -```js -describe('an essay on the best flavor', () => { - test('mentions grapefruit', () => { - expect(essayOnTheBestFlavor()).toMatch(/grapefruit/); - expect(essayOnTheBestFlavor()).toMatch(new RegExp('grapefruit')); - }); -}); -``` - -This matcher also accepts a string, which it will try to match: - -```js -describe('grapefruits are healthy', () => { - test('grapefruits are a fruit', () => { - expect('grapefruits').toMatch('fruit'); - }); -}); -``` - -### `.toMatchObject(object)` - -Use `.toMatchObject` to check that a JavaScript object matches a subset of the properties of an object. It will match received objects with properties that are **not** in the expected object. - -You can also pass an array of objects, in which case the method will return true only if each object in the received array matches (in the `toMatchObject` sense described above) the corresponding object in the expected array. This is useful if you want to check that two arrays match in their number of elements, as opposed to `arrayContaining`, which allows for extra elements in the received array. - -You can match properties against values or against matchers. - -```js -const houseForSale = { - bath: true, - bedrooms: 4, - kitchen: { - amenities: ['oven', 'stove', 'washer'], - area: 20, - wallColor: 'white', - }, -}; -const desiredHouse = { - bath: true, - kitchen: { - amenities: ['oven', 'stove', 'washer'], - wallColor: expect.stringMatching(/white|yellow/), - }, -}; - -test('the house has my desired features', () => { - expect(houseForSale).toMatchObject(desiredHouse); -}); -``` - -```js -describe('toMatchObject applied to arrays', () => { - test('the number of elements must match exactly', () => { - expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]); - }); - - test('.toMatchObject is called for each elements, so extra object properties are okay', () => { - expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([ - {foo: 'bar'}, - {baz: 1}, - ]); - }); -}); -``` - -### `.toMatchSnapshot(propertyMatchers?, hint?)` - -This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](SnapshotTesting.md) for more information. - -You can provide an optional `propertyMatchers` object argument, which has asymmetric matchers as values of a subset of expected properties, **if** the received value will be an **object** instance. It is like `toMatchObject` with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties. - -You can provide an optional `hint` string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate **multiple** snapshots in a **single** `it` or `test` block. Jest sorts snapshots by name in the corresponding `.snap` file. - -### `.toMatchInlineSnapshot(propertyMatchers?, inlineSnapshot)` - -Ensures that a value matches the most recent snapshot. - -You can provide an optional `propertyMatchers` object argument, which has asymmetric matchers as values of a subset of expected properties, **if** the received value will be an **object** instance. It is like `toMatchObject` with flexible criteria for a subset of properties, followed by a snapshot test as exact criteria for the rest of the properties. - -Jest adds the `inlineSnapshot` string argument to the matcher in the test file (instead of an external `.snap` file) the first time that the test runs. - -Check out the section on [Inline Snapshots](SnapshotTesting.md#inline-snapshots) for more info. - -### `.toStrictEqual(value)` - -Use `.toStrictEqual` to test that objects have the same structure and type. - -Differences from `.toEqual`: - -- keys with `undefined` properties are checked, e.g. `{a: undefined, b: 2}` will not equal `{b: 2}`; -- `undefined` items are taken into account, e.g. `[2]` will not equal `[2, undefined]`; -- array sparseness is checked, e.g. `[, 1]` will not equal `[undefined, 1]`; -- object types are checked, e.g. a class instance with fields `a` and `b` will not equal a literal object with fields `a` and `b`. - -```js -class LaCroix { - constructor(flavor) { - this.flavor = flavor; - } -} - -describe('the La Croix cans on my desk', () => { - test('are not semantically the same', () => { - expect(new LaCroix('lemon')).toEqual({flavor: 'lemon'}); - expect(new LaCroix('lemon')).not.toStrictEqual({flavor: 'lemon'}); - }); -}); -``` - -### `.toThrow(error?)` - -Also under the alias: `.toThrowError(error?)` - -Use `.toThrow` to test that a function throws when it is called. For example, if we want to test that `drinkFlavor('octopus')` throws, because octopus flavor is too disgusting to drink, we could write: - -```js -test('throws on octopus', () => { - expect(() => { - drinkFlavor('octopus'); - }).toThrow(); -}); -``` - -:::tip - -You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail. - -::: - -You can provide an optional argument to test that a specific error is thrown: - -- regular expression: error message **matches** the pattern -- string: error message **includes** the substring -- error object: error message is **equal to** the message property of the object -- error class: error object is **instance of** class - -For example, let's say that `drinkFlavor` is coded like this: - -```js -function drinkFlavor(flavor) { - if (flavor == 'octopus') { - throw new DisgustingFlavorError('yuck, octopus flavor'); - } - // Do some other stuff -} -``` - -We could test this error gets thrown in several ways: - -```js -test('throws on octopus', () => { - function drinkOctopus() { - drinkFlavor('octopus'); - } - - // Test that the error message says "yuck" somewhere: these are equivalent - expect(drinkOctopus).toThrow(/yuck/); - expect(drinkOctopus).toThrow('yuck'); - - // Test the exact error message - expect(drinkOctopus).toThrow(/^yuck, octopus flavor$/); - expect(drinkOctopus).toThrow(new Error('yuck, octopus flavor')); - - // Test that we get a DisgustingFlavorError - expect(drinkOctopus).toThrow(DisgustingFlavorError); -}); -``` - -### `.toThrowErrorMatchingSnapshot(hint?)` - -Use `.toThrowErrorMatchingSnapshot` to test that a function throws an error matching the most recent snapshot when it is called. - -You can provide an optional `hint` string argument that is appended to the test name. Although Jest always appends a number at the end of a snapshot name, short descriptive hints might be more useful than numbers to differentiate **multiple** snapshots in a **single** `it` or `test` block. Jest sorts snapshots by name in the corresponding `.snap` file. - -For example, let's say you have a `drinkFlavor` function that throws whenever the flavor is `'octopus'`, and is coded like this: - -```js -function drinkFlavor(flavor) { - if (flavor == 'octopus') { - throw new DisgustingFlavorError('yuck, octopus flavor'); - } - // Do some other stuff -} -``` - -The test for this function will look this way: - -```js -test('throws on octopus', () => { - function drinkOctopus() { - drinkFlavor('octopus'); - } - - expect(drinkOctopus).toThrowErrorMatchingSnapshot(); -}); -``` - -And it will generate the following snapshot: - -```js -exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`; -``` - -Check out [React Tree Snapshot Testing](/blog/2016/07/27/jest-14) for more information on snapshot testing. - -### `.toThrowErrorMatchingInlineSnapshot(inlineSnapshot)` - -Use `.toThrowErrorMatchingInlineSnapshot` to test that a function throws an error matching the most recent snapshot when it is called. - -Jest adds the `inlineSnapshot` string argument to the matcher in the test file (instead of an external `.snap` file) the first time that the test runs. - -Check out the section on [Inline Snapshots](SnapshotTesting.md#inline-snapshots) for more info. diff --git a/website/versioned_docs/version-25.x/GettingStarted.md b/website/versioned_docs/version-25.x/GettingStarted.md deleted file mode 100644 index e471cccc327b..000000000000 --- a/website/versioned_docs/version-25.x/GettingStarted.md +++ /dev/null @@ -1,175 +0,0 @@ ---- -id: getting-started -title: Getting Started ---- - -Install Jest using your favorite package manager: - -```bash npm2yarn -npm install --save-dev jest -``` - -Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a `sum.js` file: - -```javascript -function sum(a, b) { - return a + b; -} -module.exports = sum; -``` - -Then, create a file named `sum.test.js`. This will contain our actual test: - -```javascript -const sum = require('./sum'); - -test('adds 1 + 2 to equal 3', () => { - expect(sum(1, 2)).toBe(3); -}); -``` - -Add the following section to your `package.json`: - -```json -{ - "scripts": { - "test": "jest" - } -} -``` - -Finally, run `yarn test` or `npm test` and Jest will print this message: - -```bash -PASS ./sum.test.js -✓ adds 1 + 2 to equal 3 (5ms) -``` - -**You just successfully wrote your first test using Jest!** - -This test used `expect` and `toBe` to test that two values were exactly identical. To learn about the other things that Jest can test, see [Using Matchers](UsingMatchers.md). - -## Running from command line - -You can run Jest directly from the CLI (if it's globally available in your `PATH`, e.g. by `yarn global add jest` or `npm install jest --global`) with a variety of useful options. - -Here's how to run Jest on files matching `my-test`, using `config.json` as a configuration file and display a native OS notification after the run: - -```bash -jest my-test --notify --config=config.json -``` - -If you'd like to learn more about running `jest` through the command line, take a look at the [Jest CLI Options](CLI.md) page. - -## Additional Configuration - -### Generate a basic configuration file - -Based on your project, Jest will ask you a few questions and will create a basic configuration file with a short description for each option: - -```bash -jest --init -``` - -### Using Babel - -To use [Babel](https://babeljs.io/), install required dependencies: - -```bash npm2yarn -npm install --save-dev babel-jest @babel/core @babel/preset-env -``` - -Configure Babel to target your current version of Node by creating a `babel.config.js` file in the root of your project: - -```javascript title="babel.config.js" -module.exports = { - presets: [['@babel/preset-env', {targets: {node: 'current'}}]], -}; -``` - -The ideal configuration for Babel will depend on your project. See [Babel's docs](https://babeljs.io/docs/en/) for more details. - -
Making your Babel config jest-aware - -Jest will set `process.env.NODE_ENV` to `'test'` if it's not set to something else. You can use that in your configuration to conditionally setup only the compilation needed for Jest, e.g. - -```javascript title="babel.config.js" -module.exports = api => { - const isTest = api.env('test'); - // You can use isTest to determine what presets and plugins to use. - - return { - // ... - }; -}; -``` - -:::note - -`babel-jest` is automatically installed when installing Jest and will automatically transform files if a babel configuration exists in your project. To avoid this behavior, you can explicitly reset the `transform` configuration option: - -```javascript title="jest.config.js" -module.exports = { - transform: {}, -}; -``` - -::: - -
- -### Using webpack - -Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. Webpack does offer some unique challenges over other tools. Refer to the [webpack guide](Webpack.md) to get started. - -### Using parcel - -Jest can be used in projects that use [parcel-bundler](https://parceljs.org/) to manage assets, styles, and compilation similar to webpack. Parcel requires zero configuration. Refer to the official [docs](https://parceljs.org/docs/) to get started. - -### Using TypeScript - -#### Via `babel` - -Jest supports TypeScript, via Babel. First, make sure you followed the instructions on [using Babel](#using-babel) above. Next, install the `@babel/preset-typescript`: - -```bash npm2yarn -npm install --save-dev @babel/preset-typescript -``` - -Then add `@babel/preset-typescript` to the list of presets in your `babel.config.js`. - -```javascript title="babel.config.js" -module.exports = { - presets: [ - ['@babel/preset-env', {targets: {node: 'current'}}], - // highlight-next-line - '@babel/preset-typescript', - ], -}; -``` - -However, there are some [caveats](https://babeljs.io/docs/en/babel-plugin-transform-typescript#caveats) to using TypeScript with Babel. Because TypeScript support in Babel is purely transpilation, Jest will not type-check your tests as they are run. If you want that, you can use [ts-jest](https://github.com/kulshekhar/ts-jest) instead, or just run the TypeScript compiler [tsc](https://www.typescriptlang.org/docs/handbook/compiler-options.html) separately (or as part of your build process). - -#### Via `ts-jest` - -[ts-jest](https://github.com/kulshekhar/ts-jest) is a TypeScript preprocessor with source map support for Jest that lets you use Jest to test projects written in TypeScript. - -```bash npm2yarn -npm install --save-dev ts-jest -``` - -In order for Jest to transpile TypeScript with `ts-jest`, you may also need to create a [configuration](https://kulshekhar.github.io/ts-jest/docs/getting-started/installation#jest-config-file) file. - -#### Type definitions - -You may also want to install the [`@types/jest`](https://www.npmjs.com/package/@types/jest) module for the version of Jest you're using. This will help provide full typing when writing your tests with TypeScript. - -:::note - -For `@types/*` modules it's recommended to try to match the version of the associated module. For example, if you are using `26.4.0` of `jest` then using `26.4.x` of `@types/jest` is ideal. In general, try to match the major (`26`) and minor (`4`) version as closely as possible. - -::: - -```bash npm2yarn -npm install --save-dev @types/jest -``` diff --git a/website/versioned_docs/version-25.x/GlobalAPI.md b/website/versioned_docs/version-25.x/GlobalAPI.md deleted file mode 100644 index 23ba3c46b108..000000000000 --- a/website/versioned_docs/version-25.x/GlobalAPI.md +++ /dev/null @@ -1,678 +0,0 @@ ---- -id: api -title: Globals ---- - -In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them. However, if you prefer explicit imports, you can do `import {describe, expect, test} from '@jest/globals'`. - -## Methods - -import TOCInline from '@theme/TOCInline'; - - - ---- - -## Reference - -### `afterAll(fn, timeout)` - -Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. - -Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. - -This is often useful if you want to clean up some global setup state that is shared across tests. - -For example: - -```js -const globalDatabase = makeGlobalDatabase(); - -function cleanUpDatabase(db) { - db.cleanUp(); -} - -afterAll(() => { - cleanUpDatabase(globalDatabase); -}); - -test('can find things', () => { - return globalDatabase.find('thing', {}, results => { - expect(results.length).toBeGreaterThan(0); - }); -}); - -test('can insert a thing', () => { - return globalDatabase.insert('thing', makeThing(), response => { - expect(response.success).toBeTruthy(); - }); -}); -``` - -Here the `afterAll` ensures that `cleanUpDatabase` is called after all tests run. - -If `afterAll` is inside a `describe` block, it runs at the end of the describe block. - -If you want to run some cleanup after every test instead of after all tests, use `afterEach` instead. - -### `afterEach(fn, timeout)` - -Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. - -Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. - -This is often useful if you want to clean up some temporary state that is created by each test. - -For example: - -```js -const globalDatabase = makeGlobalDatabase(); - -function cleanUpDatabase(db) { - db.cleanUp(); -} - -afterEach(() => { - cleanUpDatabase(globalDatabase); -}); - -test('can find things', () => { - return globalDatabase.find('thing', {}, results => { - expect(results.length).toBeGreaterThan(0); - }); -}); - -test('can insert a thing', () => { - return globalDatabase.insert('thing', makeThing(), response => { - expect(response.success).toBeTruthy(); - }); -}); -``` - -Here the `afterEach` ensures that `cleanUpDatabase` is called after each test runs. - -If `afterEach` is inside a `describe` block, it only runs after the tests that are inside this describe block. - -If you want to run some cleanup just once, after all of the tests run, use `afterAll` instead. - -### `beforeAll(fn, timeout)` - -Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. - -Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. - -This is often useful if you want to set up some global state that will be used by many tests. - -For example: - -```js -const globalDatabase = makeGlobalDatabase(); - -beforeAll(() => { - // Clears the database and adds some testing data. - // Jest will wait for this promise to resolve before running tests. - return globalDatabase.clear().then(() => { - return globalDatabase.insert({testData: 'foo'}); - }); -}); - -// Since we only set up the database once in this example, it's important -// that our tests don't modify it. -test('can find things', () => { - return globalDatabase.find('thing', {}, results => { - expect(results.length).toBeGreaterThan(0); - }); -}); -``` - -Here the `beforeAll` ensures that the database is set up before tests run. If setup was synchronous, you could do this without `beforeAll`. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well. - -If `beforeAll` is inside a `describe` block, it runs at the beginning of the describe block. - -If you want to run something before every test instead of before any test runs, use `beforeEach` instead. - -### `beforeEach(fn, timeout)` - -Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. - -Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. - -This is often useful if you want to reset some global state that will be used by many tests. - -For example: - -```js -const globalDatabase = makeGlobalDatabase(); - -beforeEach(() => { - // Clears the database and adds some testing data. - // Jest will wait for this promise to resolve before running tests. - return globalDatabase.clear().then(() => { - return globalDatabase.insert({testData: 'foo'}); - }); -}); - -test('can find things', () => { - return globalDatabase.find('thing', {}, results => { - expect(results.length).toBeGreaterThan(0); - }); -}); - -test('can insert a thing', () => { - return globalDatabase.insert('thing', makeThing(), response => { - expect(response.success).toBeTruthy(); - }); -}); -``` - -Here the `beforeEach` ensures that the database is reset for each test. - -If `beforeEach` is inside a `describe` block, it runs for each test in the describe block. - -If you only need to run some setup code once, before any tests run, use `beforeAll` instead. - -### `describe(name, fn)` - -`describe(name, fn)` creates a block that groups together several related tests. For example, if you have a `myBeverage` object that is supposed to be delicious but not sour, you could test it with: - -```js -const myBeverage = { - delicious: true, - sour: false, -}; - -describe('my beverage', () => { - test('is delicious', () => { - expect(myBeverage.delicious).toBeTruthy(); - }); - - test('is not sour', () => { - expect(myBeverage.sour).toBeFalsy(); - }); -}); -``` - -This isn't required - you can write the `test` blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups. - -You can also nest `describe` blocks if you have a hierarchy of tests: - -```js -const binaryStringToNumber = binString => { - if (!/^[01]+$/.test(binString)) { - throw new CustomError('Not a binary number.'); - } - - return parseInt(binString, 2); -}; - -describe('binaryStringToNumber', () => { - describe('given an invalid binary string', () => { - test('composed of non-numbers throws CustomError', () => { - expect(() => binaryStringToNumber('abc')).toThrow(CustomError); - }); - - test('with extra whitespace throws CustomError', () => { - expect(() => binaryStringToNumber(' 100')).toThrow(CustomError); - }); - }); - - describe('given a valid binary string', () => { - test('returns the correct number', () => { - expect(binaryStringToNumber('100')).toBe(4); - }); - }); -}); -``` - -### `describe.each(table)(name, fn, timeout)` - -Use `describe.each` if you keep duplicating the same test suites with different data. `describe.each` allows you to write the test suite once and pass data in. - -`describe.each` is available with two APIs: - -#### 1. `describe.each(table)(name, fn, timeout)` - -- `table`: `Array` of Arrays with the arguments that are passed into the `fn` for each row. If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]`. - -- `name`: `String` the title of the test suite. - - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): - - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). - - `%s`- String. - - `%d`- Number. - - `%i` - Integer. - - `%f` - Floating point value. - - `%j` - JSON. - - `%o` - Object. - - `%#` - Index of the test case. - - `%%` - single percent sign ('%'). This does not consume an argument. -- `fn`: `Function` the suite of tests to be run, this is the function that will receive the parameters in each row as function arguments. -- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. - -Example: - -```js -describe.each([ - [1, 1, 2], - [1, 2, 3], - [2, 1, 3], -])('.add(%i, %i)', (a, b, expected) => { - test(`returns ${expected}`, () => { - expect(a + b).toBe(expected); - }); - - test(`returned value not be greater than ${expected}`, () => { - expect(a + b).not.toBeGreaterThan(expected); - }); - - test(`returned value not be less than ${expected}`, () => { - expect(a + b).not.toBeLessThan(expected); - }); -}); -``` - -#### 2. `` describe.each`table`(name, fn, timeout) `` - -- `table`: `Tagged Template Literal` - - First row of variable name column headings separated with `|` - - One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. -- `name`: `String` the title of the test suite, use `$variable` to inject test data into the suite title from the tagged template expressions. - - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` -- `fn`: `Function` the suite of tests to be run, this is the function that will receive the test data object. -- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. - -Example: - -```js -describe.each` - a | b | expected - ${1} | ${1} | ${2} - ${1} | ${2} | ${3} - ${2} | ${1} | ${3} -`('$a + $b', ({a, b, expected}) => { - test(`returns ${expected}`, () => { - expect(a + b).toBe(expected); - }); - - test(`returned value not be greater than ${expected}`, () => { - expect(a + b).not.toBeGreaterThan(expected); - }); - - test(`returned value not be less than ${expected}`, () => { - expect(a + b).not.toBeLessThan(expected); - }); -}); -``` - -### `describe.only(name, fn)` - -Also under the alias: `fdescribe(name, fn)` - -You can use `describe.only` if you want to run only one describe block: - -```js -describe.only('my beverage', () => { - test('is delicious', () => { - expect(myBeverage.delicious).toBeTruthy(); - }); - - test('is not sour', () => { - expect(myBeverage.sour).toBeFalsy(); - }); -}); - -describe('my other beverage', () => { - // ... will be skipped -}); -``` - -### `describe.only.each(table)(name, fn)` - -Also under the aliases: `fdescribe.each(table)(name, fn)` and `` fdescribe.each`table`(name, fn) `` - -Use `describe.only.each` if you want to only run specific tests suites of data driven tests. - -`describe.only.each` is available with two APIs: - -#### `describe.only.each(table)(name, fn)` - -```js -describe.only.each([ - [1, 1, 2], - [1, 2, 3], - [2, 1, 3], -])('.add(%i, %i)', (a, b, expected) => { - test(`returns ${expected}`, () => { - expect(a + b).toBe(expected); - }); -}); - -test('will not be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -#### `` describe.only.each`table`(name, fn) `` - -```js -describe.only.each` - a | b | expected - ${1} | ${1} | ${2} - ${1} | ${2} | ${3} - ${2} | ${1} | ${3} -`('returns $expected when $a is added to $b', ({a, b, expected}) => { - test('passes', () => { - expect(a + b).toBe(expected); - }); -}); - -test('will not be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -### `describe.skip(name, fn)` - -Also under the alias: `xdescribe(name, fn)` - -You can use `describe.skip` if you do not want to run the tests of a particular `describe` block: - -```js -describe('my beverage', () => { - test('is delicious', () => { - expect(myBeverage.delicious).toBeTruthy(); - }); - - test('is not sour', () => { - expect(myBeverage.sour).toBeFalsy(); - }); -}); - -describe.skip('my other beverage', () => { - // ... will be skipped -}); -``` - -Using `describe.skip` is often a cleaner alternative to temporarily commenting out a chunk of tests. Beware that the `describe` block will still run. If you have some setup that also should be skipped, do it in a `beforeAll` or `beforeEach` block. - -### `describe.skip.each(table)(name, fn)` - -Also under the aliases: `xdescribe.each(table)(name, fn)` and `` xdescribe.each`table`(name, fn) `` - -Use `describe.skip.each` if you want to stop running a suite of data driven tests. - -`describe.skip.each` is available with two APIs: - -#### `describe.skip.each(table)(name, fn)` - -```js -describe.skip.each([ - [1, 1, 2], - [1, 2, 3], - [2, 1, 3], -])('.add(%i, %i)', (a, b, expected) => { - test(`returns ${expected}`, () => { - expect(a + b).toBe(expected); // will not be run - }); -}); - -test('will be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -#### `` describe.skip.each`table`(name, fn) `` - -```js -describe.skip.each` - a | b | expected - ${1} | ${1} | ${2} - ${1} | ${2} | ${3} - ${2} | ${1} | ${3} -`('returns $expected when $a is added to $b', ({a, b, expected}) => { - test('will not be run', () => { - expect(a + b).toBe(expected); // will not be run - }); -}); - -test('will be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -### `test(name, fn, timeout)` - -Also under the alias: `it(name, fn, timeout)` - -All you need in a test file is the `test` method which runs a test. For example, let's say there's a function `inchesOfRain()` that should be zero. Your whole test could be: - -```js -test('did not rain', () => { - expect(inchesOfRain()).toBe(0); -}); -``` - -The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. - -If a **promise is returned** from `test`, Jest will wait for the promise to resolve before letting the test complete. For example, let's say `fetchBeverageList()` returns a promise that is supposed to resolve to a list that has `lemon` in it. You can test this with: - -```js -test('has lemon in it', () => { - return fetchBeverageList().then(list => { - expect(list).toContain('lemon'); - }); -}); -``` - -Even though the call to `test` will return right away, the test doesn't complete until the promise resolves. For more details, see [Testing Asynchronous Code](TestingAsyncCode.md) page. - -:::tip - -Jest will also wait if you **provide an argument to the test function**, usually called `done`. This could be handy when you want to test [callbacks](TestingAsyncCode.md#callbacks). - -::: - -### `test.each(table)(name, fn, timeout)` - -Also under the alias: `it.each(table)(name, fn)` and `` it.each`table`(name, fn) `` - -Use `test.each` if you keep duplicating the same test with different data. `test.each` allows you to write the test once and pass data in. - -`test.each` is available with two APIs: - -#### 1. `test.each(table)(name, fn, timeout)` - -- `table`: `Array` of Arrays with the arguments that are passed into the test `fn` for each row. If you pass in a 1D array of primitives, internally it will be mapped to a table i.e. `[1, 2, 3] -> [[1], [2], [3]]` -- `name`: `String` the title of the test block. - - Generate unique test titles by positionally injecting parameters with [`printf` formatting](https://nodejs.org/api/util.html#util_util_format_format_args): - - `%p` - [pretty-format](https://www.npmjs.com/package/pretty-format). - - `%s`- String. - - `%d`- Number. - - `%i` - Integer. - - `%f` - Floating point value. - - `%j` - JSON. - - `%o` - Object. - - `%#` - Index of the test case. - - `%%` - single percent sign ('%'). This does not consume an argument. -- `fn`: `Function` the test to be run, this is the function that will receive the parameters in each row as function arguments. -- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. - -Example: - -```js -test.each([ - [1, 1, 2], - [1, 2, 3], - [2, 1, 3], -])('.add(%i, %i)', (a, b, expected) => { - expect(a + b).toBe(expected); -}); -``` - -#### 2. `` test.each`table`(name, fn, timeout) `` - -- `table`: `Tagged Template Literal` - - First row of variable name column headings separated with `|` - - One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. -- `name`: `String` the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions. - - To inject nested object values use you can supply a keyPath i.e. `$variable.path.to.value` -- `fn`: `Function` the test to be run, this is the function that will receive the test data object. -- Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait for each row before aborting. The default timeout is 5 seconds. - -Example: - -```js -test.each` - a | b | expected - ${1} | ${1} | ${2} - ${1} | ${2} | ${3} - ${2} | ${1} | ${3} -`('returns $expected when $a is added to $b', ({a, b, expected}) => { - expect(a + b).toBe(expected); -}); -``` - -### `test.only(name, fn, timeout)` - -Also under the aliases: `it.only(name, fn, timeout)`, and `fit(name, fn, timeout)` - -When you are debugging a large test file, you will often only want to run a subset of tests. You can use `.only` to specify which tests are the only ones you want to run in that test file. - -Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. The default timeout is 5 seconds. - -For example, let's say you had these tests: - -```js -test.only('it is raining', () => { - expect(inchesOfRain()).toBeGreaterThan(0); -}); - -test('it is not snowing', () => { - expect(inchesOfSnow()).toBe(0); -}); -``` - -Only the "it is raining" test will run in that test file, since it is run with `test.only`. - -Usually you wouldn't check code using `test.only` into source control - you would use it for debugging, and remove it once you have fixed the broken tests. - -### `test.only.each(table)(name, fn)` - -Also under the aliases: `it.only.each(table)(name, fn)`, `fit.each(table)(name, fn)`, `` it.only.each`table`(name, fn) `` and `` fit.each`table`(name, fn) `` - -Use `test.only.each` if you want to only run specific tests with different test data. - -`test.only.each` is available with two APIs: - -#### `test.only.each(table)(name, fn)` - -```js -test.only.each([ - [1, 1, 2], - [1, 2, 3], - [2, 1, 3], -])('.add(%i, %i)', (a, b, expected) => { - expect(a + b).toBe(expected); -}); - -test('will not be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -#### `` test.only.each`table`(name, fn) `` - -```js -test.only.each` - a | b | expected - ${1} | ${1} | ${2} - ${1} | ${2} | ${3} - ${2} | ${1} | ${3} -`('returns $expected when $a is added to $b', ({a, b, expected}) => { - expect(a + b).toBe(expected); -}); - -test('will not be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -### `test.skip(name, fn)` - -Also under the aliases: `it.skip(name, fn)`, `xit(name, fn)`, and `xtest(name, fn)` - -When you are maintaining a large codebase, you may sometimes find a test that is temporarily broken for some reason. If you want to skip running this test, but you don't want to delete this code, you can use `test.skip` to specify some tests to skip. - -For example, let's say you had these tests: - -```js -test('it is raining', () => { - expect(inchesOfRain()).toBeGreaterThan(0); -}); - -test.skip('it is not snowing', () => { - expect(inchesOfSnow()).toBe(0); -}); -``` - -Only the "it is raining" test will run, since the other test is run with `test.skip`. - -You could comment the test out, but it's often a bit nicer to use `test.skip` because it will maintain indentation and syntax highlighting. - -### `test.skip.each(table)(name, fn)` - -Also under the aliases: `it.skip.each(table)(name, fn)`, `xit.each(table)(name, fn)`, `xtest.each(table)(name, fn)`, `` it.skip.each`table`(name, fn) ``, `` xit.each`table`(name, fn) `` and `` xtest.each`table`(name, fn) `` - -Use `test.skip.each` if you want to stop running a collection of data driven tests. - -`test.skip.each` is available with two APIs: - -#### `test.skip.each(table)(name, fn)` - -```js -test.skip.each([ - [1, 1, 2], - [1, 2, 3], - [2, 1, 3], -])('.add(%i, %i)', (a, b, expected) => { - expect(a + b).toBe(expected); // will not be run -}); - -test('will be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -#### `` test.skip.each`table`(name, fn) `` - -```js -test.skip.each` - a | b | expected - ${1} | ${1} | ${2} - ${1} | ${2} | ${3} - ${2} | ${1} | ${3} -`('returns $expected when $a is added to $b', ({a, b, expected}) => { - expect(a + b).toBe(expected); // will not be run -}); - -test('will be run', () => { - expect(1 / 0).toBe(Infinity); -}); -``` - -### `test.todo(name)` - -Also under the alias: `it.todo(name)` - -Use `test.todo` when you are planning on writing tests. These tests will be highlighted in the summary output at the end so you know how many tests you still need todo. - -```js -const add = (a, b) => a + b; - -test.todo('add should be associative'); -``` - -:::tip - -`test.todo` will throw an error if you pass it a test callback function. Use [`test.skip`](#testskipname-fn) instead, if you already implemented the test, but do not want it to run. - -::: diff --git a/website/versioned_docs/version-25.x/JestCommunity.md b/website/versioned_docs/version-25.x/JestCommunity.md deleted file mode 100644 index af71f2e575ae..000000000000 --- a/website/versioned_docs/version-25.x/JestCommunity.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -title: Jest Community -id: jest-community ---- - -The community around Jest is working hard to make the testing experience even greater. - -[jest-community](https://github.com/jest-community) is a new GitHub organization for high quality Jest additions curated by Jest maintainers and collaborators. It already features some of our favorite projects, to name a few: - -- [vscode-jest](https://github.com/jest-community/vscode-jest) -- [jest-extended](https://github.com/jest-community/jest-extended) -- [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) -- [awesome-jest](https://github.com/jest-community/awesome-jest) - -Community projects under one organisation are a great way for Jest to experiment with new ideas/techniques and approaches. Encourage contributions from the community and publish contributions independently at a faster pace. - -## Awesome Jest - -The jest-community org maintains an [awesome-jest](https://github.com/jest-community/awesome-jest) list of great projects and resources related to Jest. - -If you have something awesome to share, feel free to reach out to us! We'd love to share your project on the awesome-jest list ([send a PR here](https://github.com/jest-community/awesome-jest/pulls)) or if you would like to transfer your project to the jest-community org reach out to one of the owners of the org. diff --git a/website/versioned_docs/version-25.x/JestObjectAPI.md b/website/versioned_docs/version-25.x/JestObjectAPI.md deleted file mode 100644 index 3e2067dfcddc..000000000000 --- a/website/versioned_docs/version-25.x/JestObjectAPI.md +++ /dev/null @@ -1,724 +0,0 @@ ---- -id: jest-object -title: The Jest Object ---- - -The `jest` object is automatically in scope within every test file. The methods in the `jest` object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via `import {jest} from '@jest/globals'`. - -## Methods - -import TOCInline from '@theme/TOCInline'; - - - ---- - -## Mock Modules - -### `jest.disableAutomock()` - -Disables automatic mocking in the module loader. - -:::info - -Automatic mocking should be enabled via [`automock`](Configuration.md#automock-boolean) configuration option for this method to have any effect. Also see documentation of the configuration option for more details. - -::: - -Jest configuration: - -```json -{ - "automock": true -} -``` - -Example: - -```js title="utils.js" -export default { - authorize: () => { - return 'token'; - }, -}; -``` - -```js title="__tests__/disableAutomocking.js" -import utils from '../utils'; - -jest.disableAutomock(); - -test('original implementation', () => { - // now we have the original implementation, - // even if we set the automocking in a jest configuration - expect(utils.authorize()).toBe('token'); -}); -``` - -This is usually useful when you have a scenario where the number of dependencies you want to mock is far less than the number of dependencies that you don't. For example, if you're writing a test for a module that uses a large number of dependencies that can be reasonably classified as "implementation details" of the module, then you likely do not want to mock them. - -Examples of dependencies that might be considered "implementation details" are things ranging from language built-ins (e.g. `Array.prototype` methods) to highly common utility methods (e.g. `underscore`, `lodash`, array utilities, etc) and entire libraries like `React.js`. - -Returns the `jest` object for chaining. - -:::tip - -When using `babel-jest`, calls to `disableAutomock()` will automatically be hoisted to the top of the code block. Use `autoMockOff()` if you want to explicitly avoid this behavior. - -::: - -### `jest.enableAutomock()` - -Enables automatic mocking in the module loader. - -:::info - -For more details on automatic mocking see documentation of [`automock`](Configuration.md#automock-boolean) configuration option. - -::: - -Example: - -```js title="utils.js" -export default { - authorize: () => { - return 'token'; - }, - isAuthorized: secret => secret === 'wizard', -}; -``` - -```js title="__tests__/enableAutomocking.js" -jest.enableAutomock(); - -import utils from '../utils'; - -test('original implementation', () => { - // now we have the mocked implementation, - expect(utils.authorize._isMockFunction).toBeTruthy(); - expect(utils.isAuthorized._isMockFunction).toBeTruthy(); -}); -``` - -Returns the `jest` object for chaining. - -:::tip - -When using `babel-jest`, calls to `enableAutomock` will automatically be hoisted to the top of the code block. Use `autoMockOn` if you want to explicitly avoid this behavior. - -::: - -### `jest.genMockFromModule(moduleName)` - -Given the name of a module, use the automatic mocking system to generate a mocked version of the module for you. - -This is useful when you want to create a [manual mock](ManualMocks.md) that extends the automatic mock's behavior. - -Example: - -```js title="utils.js" -module.exports = { - authorize: () => { - return 'token'; - }, - isAuthorized: secret => secret === 'wizard', -}; -``` - -```js title="__tests__/genMockFromModule.test.js" -const utils = jest.genMockFromModule('../utils'); - -utils.isAuthorized = jest.fn(secret => secret === 'not wizard'); - -test('implementation created by jest.genMockFromModule', () => { - expect(jest.isMockFunction(utils.authorize)).toBe(true); - expect(utils.isAuthorized('not wizard')).toBe(true); -}); -``` - -This is how `genMockFromModule` will mock the following data types: - -#### `Function` - -Creates a new [mock function](MockFunctionAPI.md). The new function has no formal parameters and when called will return `undefined`. This functionality also applies to `async` functions. - -#### `Class` - -Creates a new class. The interface of the original class is maintained, all of the class member functions and properties will be mocked. - -#### `Object` - -Creates a new deeply cloned object. The object keys are maintained and their values are mocked. - -#### `Array` - -Creates a new empty array, ignoring the original. - -#### `Primitives` - -Creates a new property with the same primitive value as the original property. - -Example: - -```js title="example.js" -module.exports = { - function: function square(a, b) { - return a * b; - }, - asyncFunction: async function asyncSquare(a, b) { - const result = (await a) * b; - return result; - }, - class: new (class Bar { - constructor() { - this.array = [1, 2, 3]; - } - foo() {} - })(), - object: { - baz: 'foo', - bar: { - fiz: 1, - buzz: [1, 2, 3], - }, - }, - array: [1, 2, 3], - number: 123, - string: 'baz', - boolean: true, - symbol: Symbol.for('a.b.c'), -}; -``` - -```js title="__tests__/example.test.js" -const example = jest.genMockFromModule('../example'); - -test('should run example code', () => { - // creates a new mocked function with no formal arguments. - expect(example.function.name).toBe('square'); - expect(example.function).toHaveLength(0); - - // async functions get the same treatment as standard synchronous functions. - expect(example.asyncFunction.name).toBe('asyncSquare'); - expect(example.asyncFunction).toHaveLength(0); - - // creates a new class with the same interface, member functions and properties are mocked. - expect(example.class.constructor.name).toBe('Bar'); - expect(example.class.foo.name).toBe('foo'); - expect(example.class.array).toHaveLength(0); - - // creates a deeply cloned version of the original object. - expect(example.object).toEqual({ - baz: 'foo', - bar: { - fiz: 1, - buzz: [], - }, - }); - - // creates a new empty array, ignoring the original array. - expect(example.array).toHaveLength(0); - - // creates a new property with the same primitive value as the original property. - expect(example.number).toBe(123); - expect(example.string).toBe('baz'); - expect(example.boolean).toBe(true); - expect(example.symbol).toEqual(Symbol.for('a.b.c')); -}); -``` - -### `jest.mock(moduleName, factory, options)` - -Mocks a module with an auto-mocked version when it is being required. `factory` and `options` are optional. For example: - -```js title="banana.js" -module.exports = () => 'banana'; -``` - -```js title="__tests__/test.js" -jest.mock('../banana'); - -const banana = require('../banana'); // banana will be explicitly mocked. - -banana(); // will return 'undefined' because the function is auto-mocked. -``` - -The second argument can be used to specify an explicit module factory that is being run instead of using Jest's automocking feature: - -```js -jest.mock('../moduleName', () => { - return jest.fn(() => 42); -}); - -// This runs the function specified as second argument to `jest.mock`. -const moduleName = require('../moduleName'); -moduleName(); // Will return '42'; -``` - -When using the `factory` parameter for an ES6 module with a default export, the `__esModule: true` property needs to be specified. This property is normally generated by Babel / TypeScript, but here it needs to be set manually. When importing a default export, it's an instruction to import the property named `default` from the export object: - -```js -import moduleName, {foo} from '../moduleName'; - -jest.mock('../moduleName', () => { - return { - __esModule: true, - default: jest.fn(() => 42), - foo: jest.fn(() => 43), - }; -}); - -moduleName(); // Will return 42 -foo(); // Will return 43 -``` - -The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system: - -```js -jest.mock( - '../moduleName', - () => { - /* - * Custom implementation of a module that doesn't exist in JS, - * like a generated module or a native module in react-native. - */ - }, - {virtual: true}, -); -``` - -:::caution - -Importing a module in a setup file (as specified by [`setupFilesAfterEnv`](Configuration.md#setupfilesafterenv-array)) will prevent mocking for the module in question, as well as all the modules that it imports. - -::: - -Modules that are mocked with `jest.mock` are mocked only for the file that calls `jest.mock`. Another file that imports the module will get the original implementation even if it runs after the test file that mocks the module. - -Returns the `jest` object for chaining. - -### `jest.unmock(moduleName)` - -Indicates that the module system should never return a mocked version of the specified module from `require()` (e.g. that it should always return the real module). - -The most common use of this API is for specifying the module a given test intends to be testing (and thus doesn't want automatically mocked). - -Returns the `jest` object for chaining. - -### `jest.deepUnmock(moduleName)` - -Indicates that the module system should never return a mocked version of the specified module and its dependencies. - -Returns the `jest` object for chaining. - -### `jest.doMock(moduleName, factory, options)` - -When using `babel-jest`, calls to `mock` will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior. - -One example when this is useful is when you want to mock a module differently within the same file: - -```js -beforeEach(() => { - jest.resetModules(); -}); - -test('moduleName 1', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 1); - }); - const moduleName = require('../moduleName'); - expect(moduleName()).toBe(1); -}); - -test('moduleName 2', () => { - jest.doMock('../moduleName', () => { - return jest.fn(() => 2); - }); - const moduleName = require('../moduleName'); - expect(moduleName()).toBe(2); -}); -``` - -Using `jest.doMock()` with ES6 imports requires additional steps. Follow these if you don't want to use `require` in your tests: - -- We have to specify the `__esModule: true` property (see the [`jest.mock()`](#jestmockmodulename-factory-options) API for more information). -- Static ES6 module imports are hoisted to the top of the file, so instead we have to import them dynamically using `import()`. -- Finally, we need an environment which supports dynamic importing. Please see [Using Babel](GettingStarted.md#using-babel) for the initial setup. Then add the plugin [babel-plugin-dynamic-import-node](https://www.npmjs.com/package/babel-plugin-dynamic-import-node), or an equivalent, to your Babel config to enable dynamic importing in Node. - -```js -beforeEach(() => { - jest.resetModules(); -}); - -test('moduleName 1', () => { - jest.doMock('../moduleName', () => { - return { - __esModule: true, - default: 'default1', - foo: 'foo1', - }; - }); - return import('../moduleName').then(moduleName => { - expect(moduleName.default).toBe('default1'); - expect(moduleName.foo).toBe('foo1'); - }); -}); - -test('moduleName 2', () => { - jest.doMock('../moduleName', () => { - return { - __esModule: true, - default: 'default2', - foo: 'foo2', - }; - }); - return import('../moduleName').then(moduleName => { - expect(moduleName.default).toBe('default2'); - expect(moduleName.foo).toBe('foo2'); - }); -}); -``` - -Returns the `jest` object for chaining. - -### `jest.dontMock(moduleName)` - -When using `babel-jest`, calls to `unmock` will automatically be hoisted to the top of the code block. Use this method if you want to explicitly avoid this behavior. - -Returns the `jest` object for chaining. - -### `jest.setMock(moduleName, moduleExports)` - -Explicitly supplies the mock object that the module system should return for the specified module. - -On occasion, there are times where the automatically generated mock the module system would normally provide you isn't adequate enough for your testing needs. Normally under those circumstances you should write a [manual mock](ManualMocks.md) that is more adequate for the module in question. However, on extremely rare occasions, even a manual mock isn't suitable for your purposes and you need to build the mock yourself inside your test. - -In these rare scenarios you can use this API to manually fill the slot in the module system's mock-module registry. - -Returns the `jest` object for chaining. - -:::info - -It is recommended to use [`jest.mock()`](#jestmockmodulename-factory-options) instead. The `jest.mock` API's second argument is a module factory instead of the expected exported module object. - -::: - -### `jest.requireActual(moduleName)` - -Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. - -Example: - -```js -jest.mock('../myModule', () => { - // Require the original module to not be mocked... - const originalModule = jest.requireActual('../myModule'); - - return { - __esModule: true, // Use it when dealing with esModules - ...originalModule, - getRandom: jest.fn().mockReturnValue(10), - }; -}); - -const getRandom = require('../myModule').getRandom; - -getRandom(); // Always returns 10 -``` - -### `jest.requireMock(moduleName)` - -Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. - -### `jest.resetModules()` - -Resets the module registry - the cache of all required modules. This is useful to isolate modules where local state might conflict between tests. - -Example: - -```js -const sum1 = require('../sum'); -jest.resetModules(); -const sum2 = require('../sum'); -sum1 === sum2; -// > false (Both sum modules are separate "instances" of the sum module.) -``` - -Example in a test: - -```js -beforeEach(() => { - jest.resetModules(); -}); - -test('works', () => { - const sum = require('../sum'); -}); - -test('works too', () => { - const sum = require('../sum'); - // sum is a different copy of the sum module from the previous test. -}); -``` - -Returns the `jest` object for chaining. - -### `jest.isolateModules(fn)` - -`jest.isolateModules(fn)` goes a step further than `jest.resetModules()` and creates a sandbox registry for the modules that are loaded inside the callback function. This is useful to isolate specific modules for every test so that local module state doesn't conflict between tests. - -```js -let myModule; -jest.isolateModules(() => { - myModule = require('myModule'); -}); - -const otherCopyOfMyModule = require('myModule'); -``` - -## Mock Functions - -### `jest.fn(implementation?)` - -Returns a new, unused [mock function](MockFunctionAPI.md). Optionally takes a mock implementation. - -```js -const mockFn = jest.fn(); -mockFn(); -expect(mockFn).toHaveBeenCalled(); - -// With a mock implementation: -const returnsTrue = jest.fn(() => true); -console.log(returnsTrue()); // true; -``` - -### `jest.isMockFunction(fn)` - -Determines if the given function is a mocked function. - -### `jest.spyOn(object, methodName)` - -Creates a mock function similar to `jest.fn` but also tracks calls to `object[methodName]`. Returns a Jest [mock function](MockFunctionAPI.md). - -:::note - -By default, `jest.spyOn` also calls the **spied** method. This is different behavior from most other test libraries. If you want to overwrite the original function, you can use `jest.spyOn(object, methodName).mockImplementation(() => customImplementation)` or `object[methodName] = jest.fn(() => customImplementation);` - -::: - -:::tip - -Since `jest.spyOn` is a mock, you could restore the initial state by calling [`jest.restoreAllMocks`](#jestrestoreallmocks) in the body of the callback passed to the [afterEach](GlobalAPI.md#aftereachfn-timeout) hook. - -::: - -Example: - -```js -const video = { - play() { - return true; - }, -}; - -module.exports = video; -``` - -Example test: - -```js -const video = require('./video'); - -afterEach(() => { - // restore the spy created with spyOn - jest.restoreAllMocks(); -}); - -test('plays video', () => { - const spy = jest.spyOn(video, 'play'); - const isPlaying = video.play(); - - expect(spy).toHaveBeenCalled(); - expect(isPlaying).toBe(true); -}); -``` - -### `jest.spyOn(object, methodName, accessType?)` - -Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of `accessType` that can be either `'get'` or `'set'`, which proves to be useful when you want to spy on a getter or a setter, respectively. - -Example: - -```js -const video = { - // it's a getter! - get play() { - return true; - }, -}; - -module.exports = video; - -const audio = { - _volume: false, - // it's a setter! - set volume(value) { - this._volume = value; - }, - get volume() { - return this._volume; - }, -}; - -module.exports = audio; -``` - -Example test: - -```js -const audio = require('./audio'); -const video = require('./video'); - -afterEach(() => { - // restore the spy created with spyOn - jest.restoreAllMocks(); -}); - -test('plays video', () => { - const spy = jest.spyOn(video, 'play', 'get'); // we pass 'get' - const isPlaying = video.play(); - - expect(spy).toHaveBeenCalled(); - expect(isPlaying).toBe(true); -}); - -test('plays audio', () => { - const spy = jest.spyOn(audio, 'volume', 'set'); // we pass 'set' - audio.volume = 100; - - expect(spy).toHaveBeenCalled(); - expect(audio.volume).toBe(100); -}); -``` - -### `jest.clearAllMocks()` - -Clears the `mock.calls`, `mock.instances` and `mock.results` properties of all mocks. Equivalent to calling [`.mockClear()`](MockFunctionAPI.md#mockfnmockclear) on every mocked function. - -Returns the `jest` object for chaining. - -### `jest.resetAllMocks()` - -Resets the state of all mocks. Equivalent to calling [`.mockReset()`](MockFunctionAPI.md#mockfnmockreset) on every mocked function. - -Returns the `jest` object for chaining. - -### `jest.restoreAllMocks()` - -Restores all mocks back to their original value. Equivalent to calling [`.mockRestore()`](MockFunctionAPI.md#mockfnmockrestore) on every mocked function. Beware that `jest.restoreAllMocks()` only works when the mock was created with `jest.spyOn`; other mocks will require you to manually restore them. - -## Mock Timers - -### `jest.useFakeTimers()` - -Instructs Jest to use fake versions of the standard timer functions (`setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `nextTick`, `setImmediate` and `clearImmediate`). - -Returns the `jest` object for chaining. - -### `jest.useRealTimers()` - -Instructs Jest to use the real versions of the standard timer functions. - -Returns the `jest` object for chaining. - -### `jest.runAllTicks()` - -Exhausts the **micro**-task queue (usually interfaced in node via `process.nextTick`). - -When this API is called, all pending micro-tasks that have been queued via `process.nextTick` will be executed. Additionally, if those micro-tasks themselves schedule new micro-tasks, those will be continually exhausted until there are no more micro-tasks remaining in the queue. - -### `jest.runAllTimers()` - -Exhausts both the **macro**-task queue (i.e., all tasks queued by `setTimeout()`, `setInterval()`, and `setImmediate()`) and the **micro**-task queue (usually interfaced in node via `process.nextTick`). - -When this API is called, all pending macro-tasks and micro-tasks will be executed. If those tasks themselves schedule new tasks, those will be continually exhausted until there are no more tasks remaining in the queue. - -This is often useful for synchronously executing setTimeouts during a test in order to synchronously assert about some behavior that would only happen after the `setTimeout()` or `setInterval()` callbacks executed. See the [Timer mocks](TimerMocks.md) doc for more information. - -### `jest.runAllImmediates()` - -Exhausts all tasks queued by `setImmediate()`. - -### `jest.advanceTimersByTime(msToRun)` - -Executes only the macro task queue (i.e. all tasks queued by `setTimeout()` or `setInterval()` and `setImmediate()`). - -When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via `setTimeout()` or `setInterval()`, and would be executed within this time frame will be executed. Additionally, if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within `msToRun` milliseconds. - -### `jest.runOnlyPendingTimers()` - -Executes only the macro-tasks that are currently pending (i.e., only the tasks that have been queued by `setTimeout()` or `setInterval()` up to this point). If any of the currently pending macro-tasks schedule new macro-tasks, those new tasks will not be executed by this call. - -This is useful for scenarios such as one where the module being tested schedules a `setTimeout()` whose callback schedules another `setTimeout()` recursively (meaning the scheduling never stops). In these scenarios, it's useful to be able to run forward in time by a single step at a time. - -### `jest.advanceTimersToNextTimer(steps)` - -Advances all timers by the needed milliseconds so that only the next timeouts/intervals will run. - -Optionally, you can provide `steps`, so it will run `steps` amount of next timeouts/intervals. - -### `jest.clearAllTimers()` - -Removes any pending timers from the timer system. - -This means, if any timers have been scheduled (but have not yet executed), they will be cleared and will never have the opportunity to execute in the future. - -### `jest.getTimerCount()` - -Returns the number of fake timers still left to run. - -## Misc - -### `jest.retryTimes(numRetries, options?)` - -Runs failed tests n-times until they pass or until the max number of retries is exhausted. - -```js -jest.retryTimes(3); - -test('will fail', () => { - expect(true).toBe(false); -}); -``` - -Returns the `jest` object for chaining. - -:::caution - -`jest.retryTimes()` must be declared at the top level of a test file or in a `describe` block. - -::: - -:::info - -This function is only available with the default [jest-circus](https://github.com/jestjs/jest/tree/main/packages/jest-circus) runner. - -::: - -### `jest.setTimeout(timeout)` - -Set the default timeout interval (in milliseconds) for all tests and before/after hooks in the test file. This only affects the test file from which this function is called. The default timeout interval is 5 seconds if this method is not called. - -Example: - -```js -jest.setTimeout(1000); // 1 second -``` - -:::tip - -To set timeout intervals on different tests in the same file, use the [`timeout` option on each individual test](GlobalAPI.md#testname-fn-timeout). - -If you want to set the timeout for all test files, use [`testTimeout`](Configuration.md#testtimeout-number) configuration option. - -::: diff --git a/website/versioned_docs/version-25.x/JestPlatform.md b/website/versioned_docs/version-25.x/JestPlatform.md deleted file mode 100644 index 298f5cf64600..000000000000 --- a/website/versioned_docs/version-25.x/JestPlatform.md +++ /dev/null @@ -1,170 +0,0 @@ ---- -id: jest-platform -title: Jest Platform ---- - -You can cherry pick specific features of Jest and use them as standalone packages. Here's a list of the available packages: - -## jest-changed-files - -Tool for identifying modified files in a git/hg repository. Exports two functions: - -- `getChangedFilesForRoots` returns a promise that resolves to an object with the changed files and repos. -- `findRepos` returns a promise that resolves to a set of repositories contained in the specified path. - -### Example - -```javascript -const {getChangedFilesForRoots} = require('jest-changed-files'); - -// print the set of modified files since last commit in the current repo -getChangedFilesForRoots(['./'], { - lastCommit: true, -}).then(result => console.log(result.changedFiles)); -``` - -You can read more about `jest-changed-files` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-changed-files/README.md). - -## jest-diff - -Tool for visualizing changes in data. Exports a function that compares two values of any type and returns a "pretty-printed" string illustrating the difference between the two arguments. - -### Example - -```javascript -const diff = require('jest-diff'); - -const a = {a: {b: {c: 5}}}; -const b = {a: {b: {c: 6}}}; - -const result = diff(a, b); - -// print diff -console.log(result); -``` - -## jest-docblock - -Tool for extracting and parsing the comments at the top of a JavaScript file. Exports various functions to manipulate the data inside the comment block. - -### Example - -```javascript -const {parseWithComments} = require('jest-docblock'); - -const code = ` -/** - * This is a sample - * - * @flow - */ - - console.log('Hello World!'); -`; - -const parsed = parseWithComments(code); - -// prints an object with two attributes: comments and pragmas. -console.log(parsed); -``` - -You can read more about `jest-docblock` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-docblock/README.md). - -## jest-get-type - -Module that identifies the primitive type of any JavaScript value. Exports a function that returns a string with the type of the value passed as argument. - -### Example - -```javascript -const getType = require('jest-get-type'); - -const array = [1, 2, 3]; -const nullValue = null; -const undefinedValue = undefined; - -// prints 'array' -console.log(getType(array)); -// prints 'null' -console.log(getType(nullValue)); -// prints 'undefined' -console.log(getType(undefinedValue)); -``` - -## jest-validate - -Tool for validating configurations submitted by users. Exports a function that takes two arguments: the user's configuration and an object containing an example configuration and other options. The return value is an object with two attributes: - -- `hasDeprecationWarnings`, a boolean indicating whether the submitted configuration has deprecation warnings, -- `isValid`, a boolean indicating whether the configuration is correct or not. - -### Example - -```javascript -const {validate} = require('jest-validate'); - -const configByUser = { - transform: '/node_modules/my-custom-transform', -}; - -const result = validate(configByUser, { - comment: ' Documentation: http://custom-docs.com', - exampleConfig: {transform: '/node_modules/babel-jest'}, -}); - -console.log(result); -``` - -You can read more about `jest-validate` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-validate/README.md). - -## jest-worker - -Module used for parallelization of tasks. Exports a class `Worker` that takes the path of Node.js module and lets you call the module's exported methods as if they were class methods, returning a promise that resolves when the specified method finishes its execution in a forked process. - -### Example - -```javascript title="heavy-task.js" -module.exports = { - myHeavyTask: args => { - // long running CPU intensive task. - }, -}; -``` - -```javascript title="main.js" -async function main() { - const worker = new Worker(require.resolve('./heavy-task.js')); - - // run 2 tasks in parallel with different arguments - const results = await Promise.all([ - worker.myHeavyTask({foo: 'bar'}), - worker.myHeavyTask({bar: 'foo'}), - ]); - - console.log(results); -} - -main(); -``` - -You can read more about `jest-worker` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/jest-worker/README.md). - -## pretty-format - -Exports a function that converts any JavaScript value into a human-readable string. Supports all built-in JavaScript types out of the box and allows extension for application-specific types via user-defined plugins. - -### Example - -```javascript -const prettyFormat = require('pretty-format'); - -const val = {object: {}}; -val.circularReference = val; -val[Symbol('foo')] = 'foo'; -val.map = new Map([['prop', 'value']]); -val.array = [-0, Infinity, NaN]; - -console.log(prettyFormat(val)); -``` - -You can read more about `pretty-format` in the [readme file](https://github.com/jestjs/jest/blob/main/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-25.x/ManualMocks.md b/website/versioned_docs/version-25.x/ManualMocks.md deleted file mode 100644 index 62e80a9b9079..000000000000 --- a/website/versioned_docs/version-25.x/ManualMocks.md +++ /dev/null @@ -1,188 +0,0 @@ ---- -id: manual-mocks -title: Manual Mocks ---- - -Manual mocks are used to stub out functionality with mock data. For example, instead of accessing a remote resource like a website or a database, you might want to create a manual mock that allows you to use fake data. This ensures your tests will be fast and not flaky. - -## Mocking user modules - -Manual mocks are defined by writing a module in a `__mocks__/` subdirectory immediately adjacent to the module. For example, to mock a module called `user` in the `models` directory, create a file called `user.js` and put it in the `models/__mocks__` directory. - -:::caution - -The `__mocks__` folder is case-sensitive, so naming the directory `__MOCKS__` will break on some systems. - -::: - -:::note - -When we require that module in our tests (meaning we want to use the manual mock instead of the real implementation), explicitly calling `jest.mock('./moduleName')` is **required**. - -::: - -## Mocking Node modules - -If the module you are mocking is a Node module (e.g.: `lodash`), the mock should be placed in the `__mocks__` directory adjacent to `node_modules` (unless you configured [`roots`](Configuration.md#roots-arraystring) to point to a folder other than the project root) and will be **automatically** mocked. There's no need to explicitly call `jest.mock('module_name')`. - -Scoped modules (also known as [scoped packages](https://docs.npmjs.com/cli/v6/using-npm/scope)) can be mocked by creating a file in a directory structure that matches the name of the scoped module. For example, to mock a scoped module called `@scope/project-name`, create a file at `__mocks__/@scope/project-name.js`, creating the `@scope/` directory accordingly. - -:::caution - -If we want to mock Node's build-in modules (e.g.: `fs` or `path`), then explicitly calling e.g. `jest.mock('path')` is **required**, because build-in modules are not mocked by default. - -::: - -## Examples - -```bash -. -├── config -├── __mocks__ -│   └── fs.js -├── models -│   ├── __mocks__ -│   │   └── user.js -│   └── user.js -├── node_modules -└── views -``` - -When a manual mock exists for a given module, Jest's module system will use that module when explicitly calling `jest.mock('moduleName')`. However, when `automock` is set to `true`, the manual mock implementation will be used instead of the automatically created mock, even if `jest.mock('moduleName')` is not called. To opt out of this behavior you will need to explicitly call `jest.unmock('moduleName')` in tests that should use the actual module implementation. - -:::info - -In order to mock properly, Jest needs `jest.mock('moduleName')` to be in the same scope as the `require/import` statement. - -::: - -Here's a contrived example where we have a module that provides a summary of all the files in a given directory. In this case, we use the core (built in) `fs` module. - -```javascript title="FileSummarizer.js" -'use strict'; - -const fs = require('fs'); - -function summarizeFilesInDirectorySync(directory) { - return fs.readdirSync(directory).map(fileName => ({ - directory, - fileName, - })); -} - -exports.summarizeFilesInDirectorySync = summarizeFilesInDirectorySync; -``` - -Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: - -```javascript title="__mocks__/fs.js" -'use strict'; - -const path = require('path'); - -const fs = jest.genMockFromModule('fs'); - -// This is a custom function that our tests can use during setup to specify -// what the files on the "mock" filesystem should look like when any of the -// `fs` APIs are used. -let mockFiles = Object.create(null); -function __setMockFiles(newMockFiles) { - mockFiles = Object.create(null); - for (const file in newMockFiles) { - const dir = path.dirname(file); - - if (!mockFiles[dir]) { - mockFiles[dir] = []; - } - mockFiles[dir].push(path.basename(file)); - } -} - -// A custom version of `readdirSync` that reads from the special mocked out -// file list set via __setMockFiles -function readdirSync(directoryPath) { - return mockFiles[directoryPath] || []; -} - -fs.__setMockFiles = __setMockFiles; -fs.readdirSync = readdirSync; - -module.exports = fs; -``` - -Now we write our test. In this case `jest.mock('fs')` must be called explicitly, because `fs` is Node’s build-in module: - -```javascript title="__tests__/FileSummarizer-test.js" -'use strict'; - -jest.mock('fs'); - -describe('listFilesInDirectorySync', () => { - const MOCK_FILE_INFO = { - '/path/to/file1.js': 'console.log("file1 contents");', - '/path/to/file2.txt': 'file2 contents', - }; - - beforeEach(() => { - // Set up some mocked out file info before each test - require('fs').__setMockFiles(MOCK_FILE_INFO); - }); - - test('includes all files in the directory in the summary', () => { - const FileSummarizer = require('../FileSummarizer'); - const fileSummary = - FileSummarizer.summarizeFilesInDirectorySync('/path/to'); - - expect(fileSummary.length).toBe(2); - }); -}); -``` - -The example mock shown here uses [`jest.genMockFromModule`](JestObjectAPI.md#jestgenmockfrommodulemodulename) to generate an automatic mock, and overrides its default behavior. This is the recommended approach, but is completely optional. If you do not want to use the automatic mock at all, you can export your own functions from the mock file. One downside to fully manual mocks is that they're manual – meaning you have to manually update them any time the module they are mocking changes. Because of this, it's best to use or extend the automatic mock when it works for your needs. - -To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using [`jest.requireActual(moduleName)`](JestObjectAPI.md#jestrequireactualmodulename) in your manual mock and amending it with mock functions before exporting it. - -The code for this example is available at [examples/manual-mocks](https://github.com/jestjs/jest/tree/main/examples/manual-mocks). - -## Using with ES module imports - -If you're using [ES module imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) then you'll normally be inclined to put your `import` statements at the top of the test file. But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist `jest.mock` calls to the top of the module (before any imports). To learn more about this and see it in action, see [this repo](https://github.com/kentcdodds/how-jest-mocking-works). - -:::caution - -`jest.mock` calls cannot be hoisted to the top of the module if you enabled ECMAScript modules support. The ESM module loader always evaluates the static imports before executing code. See [ECMAScriptModules](ECMAScriptModules.md) for details. - -::: - -## Mocking methods which are not implemented in JSDOM - -If some code uses a method which JSDOM (the DOM implementation used by Jest) hasn't implemented yet, testing it is not easily possible. This is e.g. the case with `window.matchMedia()`. Jest returns `TypeError: window.matchMedia is not a function` and doesn't properly execute the test. - -In this case, mocking `matchMedia` in the test file should solve the issue: - -```js -Object.defineProperty(window, 'matchMedia', { - writable: true, - value: jest.fn().mockImplementation(query => ({ - matches: false, - media: query, - onchange: null, - addListener: jest.fn(), // deprecated - removeListener: jest.fn(), // deprecated - addEventListener: jest.fn(), - removeEventListener: jest.fn(), - dispatchEvent: jest.fn(), - })), -}); -``` - -This works if `window.matchMedia()` is used in a function (or method) which is invoked in the test. If `window.matchMedia()` is executed directly in the tested file, Jest reports the same error. In this case, the solution is to move the manual mock into a separate file and include this one in the test **before** the tested file: - -```js -import './matchMedia.mock'; // Must be imported before the tested file -import {myMethod} from './file-to-test'; - -describe('myMethod()', () => { - // Test the method here... -}); -``` diff --git a/website/versioned_docs/version-25.x/MigrationGuide.md b/website/versioned_docs/version-25.x/MigrationGuide.md deleted file mode 100644 index e0447b66d8ff..000000000000 --- a/website/versioned_docs/version-25.x/MigrationGuide.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -id: migration-guide -title: Migrating to Jest ---- - -If you'd like to try out Jest with an existing codebase, there are a number of ways to convert to Jest: - -- If you are using Jasmine, or a Jasmine like API (for example [Mocha](https://mochajs.org)), Jest should be mostly compatible, which makes it less complicated to migrate to. -- If you are using AVA, Expect.js (by Automattic), Jasmine, Mocha, proxyquire, Should.js or Tape you can automatically migrate with Jest Codemods (see below). -- If you like [chai](http://chaijs.com/), you can upgrade to Jest and continue using chai. However, we recommend trying out Jest's assertions and their failure messages. Jest Codemods can migrate from chai (see below). - -## jest-codemods - -If you are using [AVA](https://github.com/avajs/ava), [Chai](https://github.com/chaijs/chai), [Expect.js (by Automattic)](https://github.com/Automattic/expect.js), [Jasmine](https://github.com/jasmine/jasmine), [Mocha](https://github.com/mochajs/mocha), [proxyquire](https://github.com/thlorenz/proxyquire), [Should.js](https://github.com/shouldjs/should.js), [Tape](https://github.com/substack/tape), or [Sinon](https://sinonjs.org/) you can use the third-party [jest-codemods](https://github.com/skovhus/jest-codemods) to do most of the dirty migration work. It runs a code transformation on your codebase using [jscodeshift](https://github.com/facebook/jscodeshift). - -To transform your existing tests, navigate to the project containing the tests and run: - -```bash -npx jest-codemods -``` - -More information can be found at [https://github.com/skovhus/jest-codemods](https://github.com/skovhus/jest-codemods). diff --git a/website/versioned_docs/version-25.x/MockFunctionAPI.md b/website/versioned_docs/version-25.x/MockFunctionAPI.md deleted file mode 100644 index 9d591d222426..000000000000 --- a/website/versioned_docs/version-25.x/MockFunctionAPI.md +++ /dev/null @@ -1,487 +0,0 @@ ---- -id: mock-function-api -title: Mock Functions ---- - -Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output. You can create a mock function with `jest.fn()`. If no implementation is given, the mock function will return `undefined` when invoked. - -## Methods - -import TOCInline from '@theme/TOCInline'; - - - ---- - -## Reference - -### `mockFn.getMockName()` - -Returns the mock name string set by calling [`.mockName()`](#mockfnmocknamename). - -### `mockFn.mock.calls` - -An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call. - -For example: A mock function `f` that has been called twice, with the arguments `f('arg1', 'arg2')`, and then with the arguments `f('arg3', 'arg4')`, would have a `mock.calls` array that looks like this: - -```js -[ - ['arg1', 'arg2'], - ['arg3', 'arg4'], -]; -``` - -### `mockFn.mock.results` - -An array containing the results of all calls that have been made to this mock function. Each entry in this array is an object containing a `type` property, and a `value` property. `type` will be one of the following: - -- `'return'` - Indicates that the call completed by returning normally. -- `'throw'` - Indicates that the call completed by throwing a value. -- `'incomplete'` - Indicates that the call has not yet completed. This occurs if you test the result from within the mock function itself, or from within a function that was called by the mock. - -The `value` property contains the value that was thrown or returned. `value` is undefined when `type === 'incomplete'`. - -For example: A mock function `f` that has been called three times, returning `'result1'`, throwing an error, and then returning `'result2'`, would have a `mock.results` array that looks like this: - -```js -[ - { - type: 'return', - value: 'result1', - }, - { - type: 'throw', - value: { - /* Error instance */ - }, - }, - { - type: 'return', - value: 'result2', - }, -]; -``` - -### `mockFn.mock.instances` - -An array that contains all the object instances that have been instantiated from this mock function using `new`. - -For example: A mock function that has been instantiated twice would have the following `mock.instances` array: - -```js -const mockFn = jest.fn(); - -const a = new mockFn(); -const b = new mockFn(); - -mockFn.mock.instances[0] === a; // true -mockFn.mock.instances[1] === b; // true -``` - -### `mockFn.mockClear()` - -Clears all information stored in the [`mockFn.mock.calls`](#mockfnmockcalls), [`mockFn.mock.instances`](#mockfnmockinstances) and [`mockFn.mock.results`](#mockfnmockresults) arrays. Often this is useful when you want to clean up a mocks usage data between two assertions. - -The [`clearMocks`](configuration#clearmocks-boolean) configuration option is available to clear mocks automatically before each tests. - -:::warning - -Beware that `mockClear` will replace `mockFn.mock`, not just these three properties! You should, therefore, avoid assigning `mockFn.mock` to other variables, temporary or not, to make sure you don't access stale data. - -::: - -### `mockFn.mockReset()` - -Does everything that [`mockFn.mockClear()`](#mockfnmockclear) does, and also removes any mocked return values or implementations. - -This is useful when you want to completely reset a _mock_ back to its initial state. - -The [`resetMocks`](configuration#resetmocks-boolean) configuration option is available to reset mocks automatically before each test. - -:::info - -Resetting a mock created with `jest.spyOn()` will result in a function with no return value. - -::: - -### `mockFn.mockRestore()` - -Does everything that [`mockFn.mockReset()`](#mockfnmockreset) does, and also restores the original (non-mocked) implementation. - -This is useful when you want to mock functions in certain test cases and restore the original implementation in others. - -The [`restoreMocks`](configuration#restoremocks-boolean) configuration option is available to restore mocks automatically before each test. - -:::info - -`mockFn.mockRestore` only works when the mock was created with `jest.spyOn`. Thus you have to take care of restoration yourself when manually assigning `jest.fn()`. - -::: - -### `mockFn.mockImplementation(fn)` - -Accepts a function that should be used as the implementation of the mock. The mock itself will still record all calls that go into and instances that come from itself – the only difference is that the implementation will also be executed when the mock is called. - -:::tip - -`jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`. - -::: - -For example: - -```js -const mockFn = jest.fn().mockImplementation(scalar => 42 + scalar); -// or: jest.fn(scalar => 42 + scalar); - -const a = mockFn(0); -const b = mockFn(1); - -a === 42; // true -b === 43; // true - -mockFn.mock.calls[0][0] === 0; // true -mockFn.mock.calls[1][0] === 1; // true -``` - -`mockImplementation` can also be used to mock class constructors: - -```js title="SomeClass.js" -module.exports = class SomeClass { - m(a, b) {} -}; -``` - -```js title="OtherModule.test.js" -jest.mock('./SomeClass'); // this happens automatically with automocking -const SomeClass = require('./SomeClass'); -const mMock = jest.fn(); -SomeClass.mockImplementation(() => { - return { - m: mMock, - }; -}); - -const some = new SomeClass(); -some.m('a', 'b'); -console.log('Calls to m: ', mMock.mock.calls); -``` - -### `mockFn.mockImplementationOnce(fn)` - -Accepts a function that will be used as an implementation of the mock for one call to the mocked function. Can be chained so that multiple function calls produce different results. - -```js -const myMockFn = jest - .fn() - .mockImplementationOnce(cb => cb(null, true)) - .mockImplementationOnce(cb => cb(null, false)); - -myMockFn((err, val) => console.log(val)); // true - -myMockFn((err, val) => console.log(val)); // false -``` - -When the mocked function runs out of implementations defined with mockImplementationOnce, it will execute the default implementation set with `jest.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called: - -```js -const myMockFn = jest - .fn(() => 'default') - .mockImplementationOnce(() => 'first call') - .mockImplementationOnce(() => 'second call'); - -// 'first call', 'second call', 'default', 'default' -console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); -``` - -### `mockFn.mockName(name)` - -Accepts a string to use in test result output in place of `'jest.fn()'` to indicate which mock function is being referenced. - -For example: - -```js -const mockFn = jest.fn().mockName('mockedFunction'); -// mockFn(); -expect(mockFn).toHaveBeenCalled(); -``` - -Will result in this error: - -```bash -expect(mockedFunction).toHaveBeenCalled() - -Expected number of calls: >= 1 -Received number of calls: 0 -``` - -### `mockFn.mockReturnThis()` - -Shorthand for: - -```js -jest.fn(function () { - return this; -}); -``` - -### `mockFn.mockReturnValue(value)` - -Shorthand for: - -```js -jest.fn().mockImplementation(() => value); -``` - -Accepts a value that will be returned whenever the mock function is called. - -```js -const mock = jest.fn(); -mock.mockReturnValue(42); -mock(); // 42 -mock.mockReturnValue(43); -mock(); // 43 -``` - -### `mockFn.mockReturnValueOnce(value)` - -Shorthand for: - -```js -jest.fn().mockImplementationOnce(() => value); -``` - -Accepts a value that will be returned for one call to the mock function. Can be chained so that successive calls to the mock function return different values. When there are no more `mockReturnValueOnce` values to use, calls will return a value specified by `mockReturnValue`. - -```js -const myMockFn = jest - .fn() - .mockReturnValue('default') - .mockReturnValueOnce('first call') - .mockReturnValueOnce('second call'); - -// 'first call', 'second call', 'default', 'default' -console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); -``` - -### `mockFn.mockResolvedValue(value)` - -Shorthand for: - -```js -jest.fn().mockImplementation(() => Promise.resolve(value)); -``` - -Useful to mock async functions in async tests: - -```js -test('async test', async () => { - const asyncMock = jest.fn().mockResolvedValue(43); - - await asyncMock(); // 43 -}); -``` - -### `mockFn.mockResolvedValueOnce(value)` - -Shorthand for: - -```js -jest.fn().mockImplementationOnce(() => Promise.resolve(value)); -``` - -Useful to resolve different values over multiple async calls: - -```js -test('async test', async () => { - const asyncMock = jest - .fn() - .mockResolvedValue('default') - .mockResolvedValueOnce('first call') - .mockResolvedValueOnce('second call'); - - await asyncMock(); // first call - await asyncMock(); // second call - await asyncMock(); // default - await asyncMock(); // default -}); -``` - -### `mockFn.mockRejectedValue(value)` - -Shorthand for: - -```js -jest.fn().mockImplementation(() => Promise.reject(value)); -``` - -Useful to create async mock functions that will always reject: - -```js -test('async test', async () => { - const asyncMock = jest.fn().mockRejectedValue(new Error('Async error')); - - await asyncMock(); // throws "Async error" -}); -``` - -### `mockFn.mockRejectedValueOnce(value)` - -Shorthand for: - -```js -jest.fn().mockImplementationOnce(() => Promise.reject(value)); -``` - -Example usage: - -```js -test('async test', async () => { - const asyncMock = jest - .fn() - .mockResolvedValueOnce('first call') - .mockRejectedValueOnce(new Error('Async error')); - - await asyncMock(); // first call - await asyncMock(); // throws "Async error" -}); -``` - -## TypeScript - -Jest itself is written in [TypeScript](https://www.typescriptlang.org). - -If you are using [Create React App](https://create-react-app.dev) then the [TypeScript template](https://create-react-app.dev/docs/adding-typescript/) has everything you need to start writing tests in TypeScript. - -Otherwise, please see our [Getting Started](GettingStarted.md#using-typescript) guide for to get setup with TypeScript. - -You can see an example of using Jest with TypeScript in our [GitHub repository](https://github.com/jestjs/jest/tree/main/examples/typescript). - -### `jest.MockedFunction` - -:::tip - -`jest.MockedFunction` is available in the `@types/jest` module from version `24.9.0`. - -::: - -The following examples will assume you have an understanding of how [Jest mock functions work with JavaScript](MockFunctions.md). - -You can use `jest.MockedFunction` to represent a function that has been replaced by a Jest mock. - -Example using [automatic `jest.mock`](JestObjectAPI.md#jestmockmodulename-factory-options): - -```ts -// Assume `add` is imported and used within `calculate`. -import add from './add'; -import calculate from './calc'; - -jest.mock('./add'); - -// Our mock of `add` is now fully typed -const mockAdd = add as jest.MockedFunction; - -test('calculate calls add', () => { - calculate('Add', 1, 2); - - expect(mockAdd).toHaveBeenCalledTimes(1); - expect(mockAdd).toHaveBeenCalledWith(1, 2); -}); -``` - -Example using [`jest.fn`](JestObjectAPI.md#jestfnimplementation): - -```ts -// Here `add` is imported for its type -import add from './add'; -import calculate from './calc'; - -test('calculate calls add', () => { - // Create a new mock that can be used in place of `add`. - const mockAdd = jest.fn() as jest.MockedFunction; - - // Note: You can use the `jest.fn` type directly like this if you want: - // const mockAdd = jest.fn, Parameters>(); - // `jest.MockedFunction` is a more friendly shortcut. - - // Now we can easily set up mock implementations. - // All the `.mock*` API can now give you proper types for `add`. - // https://jestjs.io/docs/mock-function-api - - // `.mockImplementation` can now infer that `a` and `b` are `number` - // and that the returned value is a `number`. - mockAdd.mockImplementation((a, b) => { - // Yes, this mock is still adding two numbers but imagine this - // was a complex function we are mocking. - return a + b; - }); - - // `mockAdd` is properly typed and therefore accepted by - // anything requiring `add`. - calculate(mockAdd, 1, 2); - - expect(mockAdd).toHaveBeenCalledTimes(1); - expect(mockAdd).toHaveBeenCalledWith(1, 2); -}); -``` - -### `jest.MockedClass` - -:::tip - -`jest.MockedClass` is available in the `@types/jest` module from version `24.9.0`. - -::: - -The following examples will assume you have an understanding of how [Jest mock classes work with JavaScript](Es6ClassMocks.md). - -You can use `jest.MockedClass` to represent a class that has been replaced by a Jest mock. - -Converting the [ES6 Class automatic mock example](Es6ClassMocks.md#automatic-mock) would look like this: - -```ts -import SoundPlayer from '../sound-player'; -import SoundPlayerConsumer from '../sound-player-consumer'; - -jest.mock('../sound-player'); // SoundPlayer is now a mock constructor - -const SoundPlayerMock = SoundPlayer as jest.MockedClass; - -beforeEach(() => { - // Clear all instances and calls to constructor and all methods: - SoundPlayerMock.mockClear(); -}); - -it('We can check if the consumer called the class constructor', () => { - const soundPlayerConsumer = new SoundPlayerConsumer(); - expect(SoundPlayerMock).toHaveBeenCalledTimes(1); -}); - -it('We can check if the consumer called a method on the class instance', () => { - // Show that mockClear() is working: - expect(SoundPlayerMock).not.toHaveBeenCalled(); - - const soundPlayerConsumer = new SoundPlayerConsumer(); - // Constructor should have been called again: - expect(SoundPlayerMock).toHaveBeenCalledTimes(1); - - const coolSoundFileName = 'song.mp3'; - soundPlayerConsumer.playSomethingCool(); - - // mock.instances is available with automatic mocks: - const mockSoundPlayerInstance = SoundPlayerMock.mock.instances[0]; - - // However, it will not allow access to `.mock` in TypeScript as it - // is returning `SoundPlayer`. Instead, you can check the calls to a - // method like this fully typed: - expect(SoundPlayerMock.prototype.playSoundFile.mock.calls[0][0]).toBe( - coolSoundFileName, - ); - // Equivalent to above check: - expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledWith( - coolSoundFileName, - ); - expect(SoundPlayerMock.prototype.playSoundFile).toHaveBeenCalledTimes(1); -}); -``` diff --git a/website/versioned_docs/version-25.x/MockFunctions.md b/website/versioned_docs/version-25.x/MockFunctions.md deleted file mode 100644 index 974fc126ba41..000000000000 --- a/website/versioned_docs/version-25.x/MockFunctions.md +++ /dev/null @@ -1,320 +0,0 @@ ---- -id: mock-functions -title: Mock Functions ---- - -Mock functions allow you to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with `new`, and allowing test-time configuration of return values. - -There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a [`manual mock`](ManualMocks.md) to override a module dependency. - -## Using a mock function - -Let's imagine we're testing an implementation of a function `forEach`, which invokes a callback for each item in a supplied array. - -```js title="forEach.js" -export function forEach(items, callback) { - for (let index = 0; index < items.length; index++) { - callback(items[index]); - } -} -``` - -To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected. - -```js title="forEach.test.js" -import {forEach} from './forEach'; - -const mockCallback = jest.fn(x => 42 + x); - -test('forEach function', () => { - forEach([0, 1], mockCallback); - - // The mock function was called twice - expect(mockCallback.mock.calls).toHaveLength(2); - - // The first argument of the first call to the function was 0 - expect(mockCallback.mock.calls[0][0]).toBe(0); - - // The first argument of the second call to the function was 1 - expect(mockCallback.mock.calls[1][0]).toBe(1); - - // The return value of the first call to the function was 42 - expect(mockCallback.mock.results[0].value).toBe(42); -}); -``` - -## `.mock` property - -All mock functions have this special `.mock` property, which is where data about how the function has been called and what the function returned is kept. The `.mock` property also tracks the value of `this` for each call, so it is possible to inspect this as well: - -```javascript -const myMock = jest.fn(); - -const a = new myMock(); -const b = {}; -const bound = myMock.bind(b); -bound(); - -console.log(myMock.mock.instances); -// > [ , ] -``` - -These mock members are very useful in tests to assert how these functions get called, instantiated, or what they returned: - -```javascript -// The function was called exactly once -expect(someMockFunction.mock.calls).toHaveLength(1); - -// The first arg of the first call to the function was 'first arg' -expect(someMockFunction.mock.calls[0][0]).toBe('first arg'); - -// The second arg of the first call to the function was 'second arg' -expect(someMockFunction.mock.calls[0][1]).toBe('second arg'); - -// The return value of the first call to the function was 'return value' -expect(someMockFunction.mock.results[0].value).toBe('return value'); - -// This function was instantiated exactly twice -expect(someMockFunction.mock.instances.length).toBe(2); - -// The object returned by the first instantiation of this function -// had a `name` property whose value was set to 'test' -expect(someMockFunction.mock.instances[0].name).toBe('test'); -``` - -## Mock Return Values - -Mock functions can also be used to inject test values into your code during a test: - -```javascript -const myMock = jest.fn(); -console.log(myMock()); -// > undefined - -myMock.mockReturnValueOnce(10).mockReturnValueOnce('x').mockReturnValue(true); - -console.log(myMock(), myMock(), myMock(), myMock()); -// > 10, 'x', true, true -``` - -Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate the behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. - -```javascript -const filterTestFn = jest.fn(); - -// Make the mock return `true` for the first call, -// and `false` for the second call -filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false); - -const result = [11, 12].filter(num => filterTestFn(num)); - -console.log(result); -// > [11] -console.log(filterTestFn.mock.calls); -// > [ [11], [12] ] -``` - -Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. - -## Mocking Modules - -Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: - -```js title="users.js" -import axios from 'axios'; - -class Users { - static all() { - return axios.get('/users.json').then(resp => resp.data); - } -} - -export default Users; -``` - -Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the `jest.mock(...)` function to automatically mock the axios module. - -Once we mock the module we can provide a `mockResolvedValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want `axios.get('/users.json')` to return a fake response. - -```js title="users.test.js" -import axios from 'axios'; -import Users from './users'; - -jest.mock('axios'); - -test('should fetch users', () => { - const users = [{name: 'Bob'}]; - const resp = {data: users}; - axios.get.mockResolvedValue(resp); - - // or you could use the following depending on your use case: - // axios.get.mockImplementation(() => Promise.resolve(resp)) - - return Users.all().then(data => expect(data).toEqual(users)); -}); -``` - -## Mocking Partials - -Subsets of a module can be mocked and the rest of the module can keep their actual implementation: - -```js title="foo-bar-baz.js" -export const foo = 'foo'; -export const bar = () => 'bar'; -export default () => 'baz'; -``` - -```js -//test.js -import defaultExport, {bar, foo} from '../foo-bar-baz'; - -jest.mock('../foo-bar-baz', () => { - const originalModule = jest.requireActual('../foo-bar-baz'); - - //Mock the default export and named export 'foo' - return { - __esModule: true, - ...originalModule, - default: jest.fn(() => 'mocked baz'), - foo: 'mocked foo', - }; -}); - -test('should do a partial mock', () => { - const defaultExportResult = defaultExport(); - expect(defaultExportResult).toBe('mocked baz'); - expect(defaultExport).toHaveBeenCalled(); - - expect(foo).toBe('mocked foo'); - expect(bar()).toBe('bar'); -}); -``` - -## Mock Implementations - -Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. - -```javascript -const myMockFn = jest.fn(cb => cb(null, true)); - -myMockFn((err, val) => console.log(val)); -// > true -``` - -The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: - -```js title="foo.js" -module.exports = function () { - // some implementation; -}; -``` - -```js title="test.js" -jest.mock('../foo'); // this happens automatically with automocking -const foo = require('../foo'); - -// foo is a mock function -foo.mockImplementation(() => 42); -foo(); -// > 42 -``` - -When you need to recreate a complex behavior of a mock function such that multiple function calls produce different results, use the `mockImplementationOnce` method: - -```javascript -const myMockFn = jest - .fn() - .mockImplementationOnce(cb => cb(null, true)) - .mockImplementationOnce(cb => cb(null, false)); - -myMockFn((err, val) => console.log(val)); -// > true - -myMockFn((err, val) => console.log(val)); -// > false -``` - -When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): - -```javascript -const myMockFn = jest - .fn(() => 'default') - .mockImplementationOnce(() => 'first call') - .mockImplementationOnce(() => 'second call'); - -console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); -// > 'first call', 'second call', 'default', 'default' -``` - -For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: - -```javascript -const myObj = { - myMethod: jest.fn().mockReturnThis(), -}; - -// is the same as - -const otherObj = { - myMethod: jest.fn(function () { - return this; - }), -}; -``` - -## Mock Names - -You can optionally provide a name for your mock functions, which will be displayed instead of `'jest.fn()'` in the test error output. Use [`.mockName()`](MockFunctionAPI.md/#mockfnmocknamename) if you want to be able to quickly identify the mock function reporting an error in your test output. - -```javascript -const myMockFn = jest - .fn() - .mockReturnValue('default') - .mockImplementation(scalar => 42 + scalar) - .mockName('add42'); -``` - -## Custom Matchers - -Finally, in order to make it less demanding to assert how mock functions have been called, we've added some custom matcher functions for you: - -```javascript -// The mock function was called at least once -expect(mockFunc).toHaveBeenCalled(); - -// The mock function was called at least once with the specified args -expect(mockFunc).toHaveBeenCalledWith(arg1, arg2); - -// The last call to the mock function was called with the specified args -expect(mockFunc).toHaveBeenLastCalledWith(arg1, arg2); - -// All calls and the name of the mock is written as a snapshot -expect(mockFunc).toMatchSnapshot(); -``` - -These matchers are sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: - -```javascript -// The mock function was called at least once -expect(mockFunc.mock.calls.length).toBeGreaterThan(0); - -// The mock function was called at least once with the specified args -expect(mockFunc.mock.calls).toContainEqual([arg1, arg2]); - -// The last call to the mock function was called with the specified args -expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1]).toEqual([ - arg1, - arg2, -]); - -// The first arg of the last call to the mock function was `42` -// (note that there is no sugar helper for this specific of an assertion) -expect(mockFunc.mock.calls[mockFunc.mock.calls.length - 1][0]).toBe(42); - -// A snapshot will check that a mock was invoked the same number of times, -// in the same order, with the same arguments. It will also assert on the name. -expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]); -expect(mockFunc.getMockName()).toBe('a mock name'); -``` - -For a complete list of matchers, check out the [reference docs](ExpectAPI.md). diff --git a/website/versioned_docs/version-25.x/MongoDB.md b/website/versioned_docs/version-25.x/MongoDB.md deleted file mode 100644 index a67d365fd9a9..000000000000 --- a/website/versioned_docs/version-25.x/MongoDB.md +++ /dev/null @@ -1,61 +0,0 @@ ---- -id: mongodb -title: Using with MongoDB ---- - -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). - -## Use jest-mongodb Preset - -[Jest MongoDB](https://github.com/shelfio/jest-mongodb) provides all required configuration to run your tests using MongoDB. - -1. First install `@shelf/jest-mongodb` - -``` -yarn add @shelf/jest-mongodb --dev -``` - -2. Specify preset in your Jest configuration: - -```json -{ - "preset": "@shelf/jest-mongodb" -} -``` - -3. Write your test - -```js -const {MongoClient} = require('mongodb'); - -describe('insert', () => { - let connection; - let db; - - beforeAll(async () => { - connection = await MongoClient.connect(global.__MONGO_URI__, { - useNewUrlParser: true, - useUnifiedTopology: true, - }); - db = await connection.db(global.__MONGO_DB_NAME__); - }); - - afterAll(async () => { - await connection.close(); - }); - - it('should insert a doc into collection', async () => { - const users = db.collection('users'); - - const mockUser = {_id: 'some-user-id', name: 'John'}; - await users.insertOne(mockUser); - - const insertedUser = await users.findOne({_id: 'some-user-id'}); - expect(insertedUser).toEqual(mockUser); - }); -}); -``` - -There's no need to load any dependencies. - -See [documentation](https://github.com/shelfio/jest-mongodb) for details (configuring MongoDB version, etc). diff --git a/website/versioned_docs/version-25.x/MoreResources.md b/website/versioned_docs/version-25.x/MoreResources.md deleted file mode 100644 index c55840f82415..000000000000 --- a/website/versioned_docs/version-25.x/MoreResources.md +++ /dev/null @@ -1,24 +0,0 @@ ---- -id: more-resources -title: More Resources ---- - -By now you should have a good idea of how Jest can help you test your applications. If you're interested in learning more, here's some related stuff you might want to check out. - -## Browse the docs - -- Learn about [Snapshot Testing](SnapshotTesting.md), [Mock Functions](MockFunctions.md), and more in our in-depth guides. -- Migrate your existing tests to Jest by following our [migration guide](MigrationGuide.md). -- Learn how to [configure Jest](Configuration.md). -- Look at the full [API Reference](GlobalAPI.md). -- [Troubleshoot](Troubleshooting.md) problems with Jest. - -## Learn by example - -You will find a number of example test cases in the [`examples`](https://github.com/jestjs/jest/tree/main/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/main/packages/react/src/__tests__), [Relay](https://github.com/facebook/relay/tree/main/packages/react-relay/__tests__), and [React Native](https://github.com/facebook/react-native/tree/main/Libraries/Animated/__tests__) projects. - -## Join the community - -Ask questions and find answers from other Jest users like you. [Reactiflux](https://www.reactiflux.com/) is a Discord chat where a lot of Jest discussion happens. Check out the `#testing` channel. - -Follow the [Jest Twitter account](https://twitter.com/jestjs_) and [blog](/blog/) to find out what's happening in the world of Jest. diff --git a/website/versioned_docs/version-25.x/Puppeteer.md b/website/versioned_docs/version-25.x/Puppeteer.md deleted file mode 100644 index a05edd1fc702..000000000000 --- a/website/versioned_docs/version-25.x/Puppeteer.md +++ /dev/null @@ -1,175 +0,0 @@ ---- -id: puppeteer -title: Using with puppeteer ---- - -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). - -:::note - -Generating code coverage for test files using Puppeteer is currently not possible if your test uses `page.$eval`, `page.$$eval` or `page.evaluate` as the passed function is executed outside of Jest's scope. Check out [issue #7962](https://github.com/jestjs/jest/issues/7962#issuecomment-495272339) on GitHub for a workaround. - -::: - -## Use jest-puppeteer Preset - -[Jest Puppeteer](https://github.com/smooth-code/jest-puppeteer) provides all required configuration to run your tests using Puppeteer. - -1. First, install `jest-puppeteer` - -``` -yarn add --dev jest-puppeteer -``` - -2. Specify preset in your Jest configuration: - -```json -{ - "preset": "jest-puppeteer" -} -``` - -3. Write your test - -```js -describe('Google', () => { - beforeAll(async () => { - await page.goto('https://google.com'); - }); - - it('should be titled "Google"', async () => { - await expect(page.title()).resolves.toMatch('Google'); - }); -}); -``` - -There's no need to load any dependencies. Puppeteer's `page` and `browser` classes will automatically be exposed - -See [documentation](https://github.com/smooth-code/jest-puppeteer). - -## Custom example without jest-puppeteer preset - -You can also hook up puppeteer from scratch. The basic idea is to: - -1. launch & file the websocket endpoint of puppeteer with Global Setup -2. connect to puppeteer from each Test Environment -3. close puppeteer with Global Teardown - -Here's an example of the GlobalSetup script - -```js title="setup.js" -const {mkdir, writeFile} = require('fs').promises; -const os = require('os'); -const path = require('path'); -const puppeteer = require('puppeteer'); - -const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); - -module.exports = async function () { - const browser = await puppeteer.launch(); - // store the browser instance so we can teardown it later - // this global is only available in the teardown but not in TestEnvironments - global.__BROWSER_GLOBAL__ = browser; - - // use the file system to expose the wsEndpoint for TestEnvironments - await mkdir(DIR, {recursive: true}); - await writeFile(path.join(DIR, 'wsEndpoint'), browser.wsEndpoint()); -}; -``` - -Then we need a custom Test Environment for puppeteer - -```js title="puppeteer_environment.js" -const {readFile} = require('fs').promises; -const os = require('os'); -const path = require('path'); -const puppeteer = require('puppeteer'); -const NodeEnvironment = require('jest-environment-node'); - -const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); - -class PuppeteerEnvironment extends NodeEnvironment { - constructor(config) { - super(config); - } - - async setup() { - await super.setup(); - // get the wsEndpoint - const wsEndpoint = await readFile(path.join(DIR, 'wsEndpoint'), 'utf8'); - if (!wsEndpoint) { - throw new Error('wsEndpoint not found'); - } - - // connect to puppeteer - this.global.__BROWSER_GLOBAL__ = await puppeteer.connect({ - browserWSEndpoint: wsEndpoint, - }); - } - - async teardown() { - if (this.global.__BROWSER_GLOBAL__) { - this.global.__BROWSER_GLOBAL__.disconnect(); - } - await super.teardown(); - } - - runScript(script) { - return super.runScript(script); - } -} - -module.exports = PuppeteerEnvironment; -``` - -Finally, we can close the puppeteer instance and clean-up the file - -```js title="teardown.js" -const fs = require('fs').promises; -const os = require('os'); -const path = require('path'); - -const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup'); -module.exports = async function () { - // close the browser instance - await global.__BROWSER_GLOBAL__.close(); - - // clean-up the wsEndpoint file - await fs.rm(DIR, {recursive: true, force: true}); -}; -``` - -With all the things set up, we can now write our tests like this: - -```js title="test.js" -const timeout = 5000; - -describe( - '/ (Home Page)', - () => { - let page; - beforeAll(async () => { - page = await global.__BROWSER_GLOBAL__.newPage(); - await page.goto('https://google.com'); - }, timeout); - - it('should load without error', async () => { - const text = await page.evaluate(() => document.body.textContent); - expect(text).toContain('google'); - }); - }, - timeout, -); -``` - -Finally, set `jest.config.js` to read from these files. (The `jest-puppeteer` preset does something like this under the hood.) - -```js -module.exports = { - globalSetup: './setup.js', - globalTeardown: './teardown.js', - testEnvironment: './puppeteer_environment.js', -}; -``` - -Here's the code of [full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/website/versioned_docs/version-25.x/SetupAndTeardown.md b/website/versioned_docs/version-25.x/SetupAndTeardown.md deleted file mode 100644 index a45b49cb0bfe..000000000000 --- a/website/versioned_docs/version-25.x/SetupAndTeardown.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -id: setup-teardown -title: Setup and Teardown ---- - -Often while writing tests you have some setup work that needs to happen before tests run, and you have some finishing work that needs to happen after tests run. Jest provides helper functions to handle this. - -## Repeating Setup For Many Tests - -If you have some work you need to do repeatedly for many tests, you can use `beforeEach` and `afterEach`. - -For example, let's say that several tests interact with a database of cities. You have a method `initializeCityDatabase()` that must be called before each of these tests, and a method `clearCityDatabase()` that must be called after each of these tests. You can do this with: - -```js -beforeEach(() => { - initializeCityDatabase(); -}); - -afterEach(() => { - clearCityDatabase(); -}); - -test('city database has Vienna', () => { - expect(isCity('Vienna')).toBeTruthy(); -}); - -test('city database has San Juan', () => { - expect(isCity('San Juan')).toBeTruthy(); -}); -``` - -`beforeEach` and `afterEach` can handle asynchronous code in the same ways that [tests can handle asynchronous code](TestingAsyncCode.md) - they can either take a `done` parameter or return a promise. For example, if `initializeCityDatabase()` returned a promise that resolved when the database was initialized, we would want to return that promise: - -```js -beforeEach(() => { - return initializeCityDatabase(); -}); -``` - -## One-Time Setup - -In some cases, you only need to do setup once, at the beginning of a file. This can be especially bothersome when the setup is asynchronous, so you can't do it inline. Jest provides `beforeAll` and `afterAll` to handle this situation. - -For example, if both `initializeCityDatabase` and `clearCityDatabase` returned promises, and the city database could be reused between tests, we could change our test code to: - -```js -beforeAll(() => { - return initializeCityDatabase(); -}); - -afterAll(() => { - return clearCityDatabase(); -}); - -test('city database has Vienna', () => { - expect(isCity('Vienna')).toBeTruthy(); -}); - -test('city database has San Juan', () => { - expect(isCity('San Juan')).toBeTruthy(); -}); -``` - -## Scoping - -The top level `before*` and `after*` hooks apply to every test in a file. The hooks declared inside a `describe` block apply only to the tests within that `describe` block. - -For example, let's say we had not just a city database, but also a food database. We could do different setup for different tests: - -```js -// Applies to all tests in this file -beforeEach(() => { - return initializeCityDatabase(); -}); - -test('city database has Vienna', () => { - expect(isCity('Vienna')).toBeTruthy(); -}); - -test('city database has San Juan', () => { - expect(isCity('San Juan')).toBeTruthy(); -}); - -describe('matching cities to foods', () => { - // Applies only to tests in this describe block - beforeEach(() => { - return initializeFoodDatabase(); - }); - - test('Vienna <3 veal', () => { - expect(isValidCityFoodPair('Vienna', 'Wiener Schnitzel')).toBe(true); - }); - - test('San Juan <3 plantains', () => { - expect(isValidCityFoodPair('San Juan', 'Mofongo')).toBe(true); - }); -}); -``` - -Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. - -```js -beforeAll(() => console.log('1 - beforeAll')); -afterAll(() => console.log('1 - afterAll')); -beforeEach(() => console.log('1 - beforeEach')); -afterEach(() => console.log('1 - afterEach')); -test('', () => console.log('1 - test')); -describe('Scoped / Nested block', () => { - beforeAll(() => console.log('2 - beforeAll')); - afterAll(() => console.log('2 - afterAll')); - beforeEach(() => console.log('2 - beforeEach')); - afterEach(() => console.log('2 - afterEach')); - test('', () => console.log('2 - test')); -}); - -// 1 - beforeAll -// 1 - beforeEach -// 1 - test -// 1 - afterEach -// 2 - beforeAll -// 1 - beforeEach -// 2 - beforeEach -// 2 - test -// 2 - afterEach -// 1 - afterEach -// 2 - afterAll -// 1 - afterAll -``` - -## Order of execution of describe and test blocks - -Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown inside `before*` and `after*` handlers rather than inside the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on. - -Consider the following illustrative test file and output: - -```js -describe('outer', () => { - console.log('describe outer-a'); - - describe('describe inner 1', () => { - console.log('describe inner 1'); - test('test 1', () => { - console.log('test for describe inner 1'); - expect(true).toBe(true); - }); - }); - - console.log('describe outer-b'); - - test('test 1', () => { - console.log('test for describe outer'); - expect(true).toBe(true); - }); - - describe('describe inner 2', () => { - console.log('describe inner 2'); - test('test for describe inner 2', () => { - console.log('test for describe inner 2'); - expect(false).toBe(false); - }); - }); - - console.log('describe outer-c'); -}); - -// describe outer-a -// describe inner 1 -// describe outer-b -// describe inner 2 -// describe outer-c -// test for describe inner 1 -// test for describe outer -// test for describe inner 2 -``` - -## General Advice - -If a test is failing, one of the first things to check should be whether the test is failing when it's the only test that runs. To run only one test with Jest, temporarily change that `test` command to a `test.only`: - -```js -test.only('this will be the only test that runs', () => { - expect(true).toBe(false); -}); - -test('this test will not run', () => { - expect('A').toBe('A'); -}); -``` - -If you have a test that often fails when it's run as part of a larger suite, but doesn't fail when you run it alone, it's a good bet that something from a different test is interfering with this one. You can often fix this by clearing some shared state with `beforeEach`. If you're not sure whether some shared state is being modified, you can also try a `beforeEach` that logs data. diff --git a/website/versioned_docs/version-25.x/SnapshotTesting.md b/website/versioned_docs/version-25.x/SnapshotTesting.md deleted file mode 100644 index 952ae6a508c2..000000000000 --- a/website/versioned_docs/version-25.x/SnapshotTesting.md +++ /dev/null @@ -1,332 +0,0 @@ ---- -id: snapshot-testing -title: Snapshot Testing ---- - -Snapshot tests are a very useful tool whenever you want to make sure your UI does not change unexpectedly. - -A typical snapshot test case renders a UI component, takes a snapshot, then compares it to a reference snapshot file stored alongside the test. The test will fail if the two snapshots do not match: either the change is unexpected, or the reference snapshot needs to be updated to the new version of the UI component. - -## Snapshot Testing with Jest - -A similar approach can be taken when it comes to testing your React components. Instead of rendering the graphical UI, which would require building the entire app, you can use a test renderer to quickly generate a serializable value for your React tree. Consider this [example test](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/link.test.js) for a [Link component](https://github.com/jestjs/jest/blob/main/examples/snapshot/Link.js): - -```tsx -import React from 'react'; -import renderer from 'react-test-renderer'; -import Link from '../Link'; - -it('renders correctly', () => { - const tree = renderer - .create(Facebook) - .toJSON(); - expect(tree).toMatchSnapshot(); -}); -``` - -The first time this test is run, Jest creates a [snapshot file](https://github.com/jestjs/jest/blob/main/examples/snapshot/__tests__/__snapshots__/link.test.js.snap) that looks like this: - -```javascript -exports[`renders correctly 1`] = ` - - Facebook - -`; -``` - -The snapshot artifact should be committed alongside code changes, and reviewed as part of your code review process. Jest uses [pretty-format](https://github.com/jestjs/jest/tree/main/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs, Jest will compare the rendered output with the previous snapshot. If they match, the test will pass. If they don't match, either the test runner found a bug in your code (in the `` component in this case) that should be fixed, or the implementation has changed and the snapshot needs to be updated. - -:::note - -The snapshot is directly scoped to the data you render – in our example the `` component with `page` prop passed to it. This implies that even if any other file has missing props (say, `App.js`) in the `` component, it will still pass the test as the test doesn't know the usage of `` component and it's scoped only to the `Link.js`. Also, rendering the same component with different props in other snapshot tests will not affect the first one, as the tests don't know about each other. - -::: - -:::info - -More information on how snapshot testing works and why we built it can be found on the [release blog post](/blog/2016/07/27/jest-14). We recommend reading [this blog post](http://benmccormick.org/2016/09/19/testing-with-jest-snapshots-first-impressions/) to get a good sense of when you should use snapshot testing. We also recommend watching this [egghead video](https://egghead.io/lessons/javascript-use-jest-s-snapshot-testing-feature?pl=testing-javascript-with-jest-a36c4074) on Snapshot Testing with Jest. - -::: - -### Updating Snapshots - -It's straightforward to spot when a snapshot test fails after a bug has been introduced. When that happens, go ahead and fix the issue and make sure your snapshot tests are passing again. Now, let's talk about the case when a snapshot test is failing due to an intentional implementation change. - -One such situation can arise if we intentionally change the address the Link component in our example is pointing to. - -```tsx -// Updated test case with a Link to a different address -it('renders correctly', () => { - const tree = renderer - .create(Instagram) - .toJSON(); - expect(tree).toMatchSnapshot(); -}); -``` - -In that case, Jest will print this output: - -![](/img/content/failedSnapshotTest.png) - -Since we just updated our component to point to a different address, it's reasonable to expect changes in the snapshot for this component. Our snapshot test case is failing because the snapshot for our updated component no longer matches the snapshot artifact for this test case. - -To resolve this, we will need to update our snapshot artifacts. You can run Jest with a flag that will tell it to re-generate snapshots: - -```bash -jest --updateSnapshot -``` - -Go ahead and accept the changes by running the above command. You may also use the equivalent single-character `-u` flag to re-generate snapshots if you prefer. This will re-generate snapshot artifacts for all failing snapshot tests. If we had any additional failing snapshot tests due to an unintentional bug, we would need to fix the bug before re-generating snapshots to avoid recording snapshots of the buggy behavior. - -If you'd like to limit which snapshot test cases get re-generated, you can pass an additional `--testNamePattern` flag to re-record snapshots only for those tests that match the pattern. - -You can try out this functionality by cloning the [snapshot example](https://github.com/jestjs/jest/tree/main/examples/snapshot), modifying the `Link` component, and running Jest. - -### Interactive Snapshot Mode - -Failed snapshots can also be updated interactively in watch mode: - -![](/img/content/interactiveSnapshot.png) - -Once you enter Interactive Snapshot Mode, Jest will step you through the failed snapshots one test at a time and give you the opportunity to review the failed output. - -From here you can choose to update that snapshot or skip to the next: - -![](/img/content/interactiveSnapshotUpdate.gif) - -Once you're finished, Jest will give you a summary before returning back to watch mode: - -![](/img/content/interactiveSnapshotDone.png) - -### Inline Snapshots - -Inline snapshots behave identically to external snapshots (`.snap` files), except the snapshot values are written automatically back into the source code. This means you can get the benefits of automatically generated snapshots without having to switch to an external file to make sure the correct value was written. - -:::info - -Inline snapshots are powered by [Prettier](https://prettier.io). To use inline snapshots you must have `prettier` installed in your project. Your Prettier configuration will be respected when writing to test files. - -If you have `prettier` installed in a location where Jest can't find it, you can tell Jest how to find it using the [`prettierPath`](./Configuration.md#prettierpath-string) configuration property. - -::: - -Example: - -First, you write a test, calling `.toMatchInlineSnapshot()` with no arguments: - -```tsx -it('renders correctly', () => { - const tree = renderer - .create(Prettier) - .toJSON(); - expect(tree).toMatchInlineSnapshot(); -}); -``` - -The next time you run Jest, `tree` will be evaluated, and a snapshot will be written as an argument to `toMatchInlineSnapshot`: - -```tsx -it('renders correctly', () => { - const tree = renderer - .create(Prettier) - .toJSON(); - expect(tree).toMatchInlineSnapshot(` - - Prettier - -`); -}); -``` - -That's all there is to it! You can even update the snapshots with `--updateSnapshot` or using the `u` key in `--watch` mode. - -The writing of snapshots into your source code is performed via [prettier](https://www.npmjs.com/package/prettier). If you're not already using it in your project but want to use inline snapshots, you'll just need to install it under your `devDependencies`. - -### Property Matchers - -Often there are fields in the object you want to snapshot which are generated (like IDs and Dates). If you try to snapshot these objects, they will force the snapshot to fail on every run: - -```javascript -it('will fail every time', () => { - const user = { - createdAt: new Date(), - id: Math.floor(Math.random() * 20), - name: 'LeBron James', - }; - - expect(user).toMatchSnapshot(); -}); - -// Snapshot -exports[`will fail every time 1`] = ` -Object { - "createdAt": 2018-05-19T23:36:09.816Z, - "id": 3, - "name": "LeBron James", -} -`; -``` - -For these cases, Jest allows providing an asymmetric matcher for any property. These matchers are checked before the snapshot is written or tested, and then saved to the snapshot file instead of the received value: - -```javascript -it('will check the matchers and pass', () => { - const user = { - createdAt: new Date(), - id: Math.floor(Math.random() * 20), - name: 'LeBron James', - }; - - expect(user).toMatchSnapshot({ - createdAt: expect.any(Date), - id: expect.any(Number), - }); -}); - -// Snapshot -exports[`will check the matchers and pass 1`] = ` -Object { - "createdAt": Any, - "id": Any, - "name": "LeBron James", -} -`; -``` - -Any given value that is not a matcher will be checked exactly and saved to the snapshot: - -```javascript -it('will check the values and pass', () => { - const user = { - createdAt: new Date(), - name: 'Bond... James Bond', - }; - - expect(user).toMatchSnapshot({ - createdAt: expect.any(Date), - name: 'Bond... James Bond', - }); -}); - -// Snapshot -exports[`will check the values and pass 1`] = ` -Object { - "createdAt": Any, - "name": 'Bond... James Bond', -} -`; -``` - -## Best Practices - -Snapshots are a fantastic tool for identifying unexpected interface changes within your application – whether that interface is an API response, UI, logs, or error messages. As with any testing strategy, there are some best-practices you should be aware of, and guidelines you should follow, in order to use them effectively. - -### 1. Treat snapshots as code - -Commit snapshots and review them as part of your regular code review process. This means treating snapshots as you would any other type of test or code in your project. - -Ensure that your snapshots are readable by keeping them focused, short, and by using tools that enforce these stylistic conventions. - -As mentioned previously, Jest uses [`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make snapshots human-readable, but you may find it useful to introduce additional tools, like [`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with its [`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/main/docs/rules/no-large-snapshots.md) option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with its component snapshot comparison feature, to promote committing short, focused assertions. - -The goal is to make it easy to review snapshots in pull requests, and fight against the habit of regenerating snapshots when test suites fail instead of examining the root causes of their failure. - -### 2. Tests should be deterministic - -Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. - -For example, if you have a [Clock](https://github.com/jestjs/jest/blob/main/examples/snapshot/Clock.js) component that uses `Date.now()`, the snapshot generated from this component will be different every time the test case is run. In this case we can [mock the Date.now() method](MockFunctions.md) to return a consistent value every time the test is run: - -```js -Date.now = jest.fn(() => 1482363367071); -``` - -Now, every time the snapshot test case runs, `Date.now()` will return `1482363367071` consistently. This will result in the same snapshot being generated for this component regardless of when the test is run. - -### 3. Use descriptive snapshot names - -Always strive to use descriptive test and/or snapshot names for snapshots. The best names describe the expected snapshot content. This makes it easier for reviewers to verify the snapshots during review, and for anyone to know whether or not an outdated snapshot is the correct behavior before updating. - -For example, compare: - -```js -exports[` should handle some test case`] = `null`; - -exports[` should handle some other test case`] = ` -
- Alan Turing -
-`; -``` - -To: - -```js -exports[` should render null`] = `null`; - -exports[` should render Alan Turing`] = ` -
- Alan Turing -
-`; -``` - -Since the latter describes exactly what's expected in the output, it's more clear to see when it's wrong: - -```js -exports[` should render null`] = ` -
- Alan Turing -
-`; - -exports[` should render Alan Turing`] = `null`; -``` - -## Frequently Asked Questions - -### Are snapshots written automatically on Continuous Integration (CI) systems? - -No, as of Jest 20, snapshots in Jest are not automatically written when Jest is run in a CI system without explicitly passing `--updateSnapshot`. It is expected that all snapshots are part of the code that is run on CI and since new snapshots automatically pass, they should not pass a test run on a CI system. It is recommended to always commit all snapshots and to keep them in version control. - -### Should snapshot files be committed? - -Yes, all snapshot files should be committed alongside the modules they are covering and their tests. They should be considered part of a test, similar to the value of any other assertion in Jest. In fact, snapshots represent the state of the source modules at any given point in time. In this way, when the source modules are modified, Jest can tell what changed from the previous version. It can also provide a lot of additional context during code review in which reviewers can study your changes better. - -### Does snapshot testing only work with React components? - -[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/jestjs/jest/blob/main/e2e/__tests__/console.test.ts) in the Jest repo. - -### What's the difference between snapshot testing and visual regression testing? - -Snapshot testing and visual regression testing are two distinct ways of testing UIs, and they serve different purposes. Visual regression testing tools take screenshots of web pages and compare the resulting images pixel by pixel. With Snapshot testing values are serialized, stored within text files, and compared using a diff algorithm. There are different trade-offs to consider and we listed the reasons why snapshot testing was built in the [Jest blog](https://jestjs.io/blog/2016/07/27/jest-14#why-snapshot-testing). - -### Does snapshot testing replace unit testing? - -Snapshot testing is only one of more than 20 assertions that ship with Jest. The aim of snapshot testing is not to replace existing unit tests, but to provide additional value and make testing painless. In some scenarios, snapshot testing can potentially remove the need for unit testing for a particular set of functionalities (e.g. React components), but they can work together as well. - -### What is the performance of snapshot testing regarding speed and size of the generated files? - -Jest has been rewritten with performance in mind, and snapshot testing is not an exception. Since snapshots are stored within text files, this way of testing is fast and reliable. Jest generates a new file for each test file that invokes the `toMatchSnapshot` matcher. The size of the snapshots is pretty small: For reference, the size of all snapshot files in the Jest codebase itself is less than 300 KB. - -### How do I resolve conflicts within snapshot files? - -Snapshot files must always represent the current state of the modules they are covering. Therefore, if you are merging two branches and encounter a conflict in the snapshot files, you can either resolve the conflict manually or update the snapshot file by running Jest and inspecting the result. - -### Is it possible to apply test-driven development principles with snapshot testing? - -Although it is possible to write snapshot files manually, that is usually not approachable. Snapshots help to figure out whether the output of the modules covered by tests is changed, rather than giving guidance to design the code in the first place. - -### Does code coverage work with snapshot testing? - -Yes, as well as with any other test. diff --git a/website/versioned_docs/version-25.x/TestingAsyncCode.md b/website/versioned_docs/version-25.x/TestingAsyncCode.md deleted file mode 100644 index 077ac3107b39..000000000000 --- a/website/versioned_docs/version-25.x/TestingAsyncCode.md +++ /dev/null @@ -1,144 +0,0 @@ ---- -id: asynchronous -title: Testing Asynchronous Code ---- - -It's common in JavaScript for code to run asynchronously. When you have code that runs asynchronously, Jest needs to know when the code it is testing has completed, before it can move on to another test. Jest has several ways to handle this. - -## Promises - -Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will fail. - -For example, let's say that `fetchData` returns a promise that is supposed to resolve to the string `'peanut butter'`. We could test it with: - -```js -test('the data is peanut butter', () => { - return fetchData().then(data => { - expect(data).toBe('peanut butter'); - }); -}); -``` - -## Async/Await - -Alternatively, you can use `async` and `await` in your tests. To write an async test, use the `async` keyword in front of the function passed to `test`. For example, the same `fetchData` scenario can be tested with: - -```js -test('the data is peanut butter', async () => { - const data = await fetchData(); - expect(data).toBe('peanut butter'); -}); - -test('the fetch fails with an error', async () => { - expect.assertions(1); - try { - await fetchData(); - } catch (e) { - expect(e).toMatch('error'); - } -}); -``` - -You can combine `async` and `await` with `.resolves` or `.rejects`. - -```js -test('the data is peanut butter', async () => { - await expect(fetchData()).resolves.toBe('peanut butter'); -}); - -test('the fetch fails with an error', async () => { - await expect(fetchData()).rejects.toMatch('error'); -}); -``` - -In these cases, `async` and `await` are effectively syntactic sugar for the same logic as the promises example uses. - -:::caution - -Be sure to return (or `await`) the promise - if you omit the `return`/`await` statement, your test will complete before the promise returned from `fetchData` resolves or rejects. - -::: - -If you expect a promise to be rejected, use the `.catch` method. Make sure to add `expect.assertions` to verify that a certain number of assertions are called. Otherwise, a fulfilled promise would not fail the test. - -```js -test('the fetch fails with an error', () => { - expect.assertions(1); - return fetchData().catch(e => expect(e).toMatch('error')); -}); -``` - -## Callbacks - -If you don't use promises, you can use callbacks. For example, let's say that `fetchData`, instead of returning a promise, expects a callback, i.e. fetches some data and calls `callback(null, data)` when it is complete. You want to test that this returned data is the string `'peanut butter'`. - -By default, Jest tests complete once they reach the end of their execution. That means this test will _not_ work as intended: - -```js -// Don't do this! -test('the data is peanut butter', () => { - function callback(error, data) { - if (error) { - throw error; - } - expect(data).toBe('peanut butter'); - } - - fetchData(callback); -}); -``` - -The problem is that the test will complete as soon as `fetchData` completes, before ever calling the callback. - -There is an alternate form of `test` that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called `done`. Jest will wait until the `done` callback is called before finishing the test. - -```js -test('the data is peanut butter', done => { - function callback(error, data) { - if (error) { - done(error); - return; - } - try { - expect(data).toBe('peanut butter'); - done(); - } catch (error) { - done(error); - } - } - - fetchData(callback); -}); -``` - -If `done()` is never called, the test will fail (with timeout error), which is what you want to happen. - -If the `expect` statement fails, it throws an error and `done()` is not called. If we want to see in the test log why it failed, we have to wrap `expect` in a `try` block and pass the error in the `catch` block to `done`. Otherwise, we end up with an opaque timeout error that doesn't show what value was received by `expect(data)`. - -:::caution - -`done()` should not be mixed with promises as this tends to lead to memory leaks in your tests. - -::: - -## `.resolves` / `.rejects` - -You can also use the `.resolves` matcher in your expect statement, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail. - -```js -test('the data is peanut butter', () => { - return expect(fetchData()).resolves.toBe('peanut butter'); -}); -``` - -Be sure to return the assertion—if you omit this `return` statement, your test will complete before the promise returned from `fetchData` is resolved and then() has a chance to execute the callback. - -If you expect a promise to be rejected, use the `.rejects` matcher. It works analogically to the `.resolves` matcher. If the promise is fulfilled, the test will automatically fail. - -```js -test('the fetch fails with an error', () => { - return expect(fetchData()).rejects.toMatch('error'); -}); -``` - -None of these forms is particularly superior to the others, and you can mix and match them across a codebase or even in a single file. It just depends on which style you feel makes your tests simpler. diff --git a/website/versioned_docs/version-25.x/TestingFrameworks.md b/website/versioned_docs/version-25.x/TestingFrameworks.md deleted file mode 100644 index 6ae4358fdf7d..000000000000 --- a/website/versioned_docs/version-25.x/TestingFrameworks.md +++ /dev/null @@ -1,49 +0,0 @@ ---- -id: testing-frameworks -title: Testing Web Frameworks ---- - -Jest is a universal testing platform, with the ability to adapt to any JavaScript library or framework. In this section, we'd like to link to community posts and articles about integrating Jest into popular JS libraries. - -## React - -- [Testing ReactJS components with Jest](https://testing-library.com/docs/react-testing-library/example-intro) by Kent C. Dodds ([@kentcdodds](https://twitter.com/kentcdodds)) - -## Vue.js - -- [Testing Vue.js components with Jest](https://alexjoverm.github.io/series/Unit-Testing-Vue-js-Components-with-the-Official-Vue-Testing-Tools-and-Jest/) by Alex Jover Morales ([@alexjoverm](https://twitter.com/alexjoverm)) -- [Jest for all: Episode 1 — Vue.js](https://medium.com/@kentaromiura_the_js_guy/jest-for-all-episode-1-vue-js-d616bccbe186#.d573vrce2) by Cristian Carlesso ([@kentaromiura](https://twitter.com/kentaromiura)) - -## AngularJS - -- [Testing an AngularJS app with Jest](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251) by Matthieu Lux ([@Swiip](https://twitter.com/Swiip)) -- [Running AngularJS Tests with Jest](https://engineering.talentpair.com/running-angularjs-tests-with-jest-49d0cc9c6d26) by Ben Brandt ([@benjaminbrandt](https://twitter.com/benjaminbrandt)) -- [AngularJS Unit Tests with Jest Actions (Traditional Chinese)](https://dwatow.github.io/2019/08-14-angularjs/angular-jest/?fbclid=IwAR2SrqYg_o6uvCQ79FdNPeOxs86dUqB6pPKgd9BgnHt1kuIDRyRM-ch11xg) by Chris Wang ([@dwatow](https://github.com/dwatow)) - -## Angular - -- [Testing Angular faster with Jest](https://www.xfive.co/blog/testing-angular-faster-jest/) by Michał Pierzchała ([@thymikee](https://twitter.com/thymikee)) - -## MobX - -- [How to Test React and MobX with Jest](https://semaphoreci.com/community/tutorials/how-to-test-react-and-mobx-with-jest) by Will Stern ([@willsterndev](https://twitter.com/willsterndev)) - -## Redux - -- [Writing Tests](https://redux.js.org/recipes/writing-tests) by Redux docs - -## Express.js - -- [How to test Express.js with Jest and Supertest](http://www.albertgao.xyz/2017/05/24/how-to-test-expressjs-with-jest-and-supertest/) by Albert Gao ([@albertgao](https://twitter.com/albertgao)) - -## GatsbyJS - -- [Unit Testing](https://www.gatsbyjs.org/docs/unit-testing/) by GatsbyJS docs - -## Hapi.js - -- [Testing Hapi.js With Jest](https://github.com/sivasankars/testing-hapi.js-with-jest) by Niralar - -## Next.js - -- [Jest and React Testing Library](https://nextjs.org/docs/testing#jest-and-react-testing-library) by Next.js docs diff --git a/website/versioned_docs/version-25.x/TimerMocks.md b/website/versioned_docs/version-25.x/TimerMocks.md deleted file mode 100644 index 58794c6a190a..000000000000 --- a/website/versioned_docs/version-25.x/TimerMocks.md +++ /dev/null @@ -1,185 +0,0 @@ ---- -id: timer-mocks -title: Timer Mocks ---- - -The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=QZoJ2Pt27BY) - -```javascript title="timerGame.js" -'use strict'; - -function timerGame(callback) { - console.log('Ready....go!'); - setTimeout(() => { - console.log("Time's up -- stop!"); - callback && callback(); - }, 1000); -} - -module.exports = timerGame; -``` - -```javascript title="__tests__/timerGame-test.js" -'use strict'; - -jest.useFakeTimers(); // or you can set "timers": "fake" globally in configuration file -jest.spyOn(global, 'setTimeout'); - -test('waits 1 second before ending the game', () => { - const timerGame = require('../timerGame'); - timerGame(); - - expect(setTimeout).toHaveBeenCalledTimes(1); - expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000); -}); -``` - -Here we enable fake timers by calling `jest.useFakeTimers()`. This mocks out `setTimeout` and other timer functions with mock functions. Timers can be restored to their normal behavior with `jest.useRealTimers()`. - -While you can call `jest.useFakeTimers()` or `jest.useRealTimers()` from anywhere (top level, inside an `it` block, etc.), it is a **global operation** and will affect other tests within the same file. Additionally, you need to call `jest.useFakeTimers()` to reset internal counters before each test. If you plan to not use fake timers in all your tests, you will want to clean up manually, as otherwise the faked timers will leak across tests: - -```javascript -afterEach(() => { - jest.useRealTimers(); -}); - -test('do something with fake timers', () => { - jest.useFakeTimers(); - // ... -}); - -test('do something with real timers', () => { - // ... -}); -``` - -Currently, two implementations of the fake timers are included - `modern` and `legacy`, where `modern` is the default one. See [configuration](Configuration.md#timers-string) for how to configure it. - -## Run All Timers - -Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test: - -```javascript -jest.useFakeTimers(); -test('calls the callback after 1 second', () => { - const timerGame = require('../timerGame'); - const callback = jest.fn(); - - timerGame(callback); - - // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); - - // Fast-forward until all timers have been executed - jest.runAllTimers(); - - // Now our callback should have been called! - expect(callback).toBeCalled(); - expect(callback).toHaveBeenCalledTimes(1); -}); -``` - -## Run Pending Timers - -There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop, throwing the following error: - -``` -Ran 100000 timers, and there are still more! Assuming we've hit an infinite recursion and bailing out... -``` - -So something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: - -```javascript title="infiniteTimerGame.js" -'use strict'; - -function infiniteTimerGame(callback) { - console.log('Ready....go!'); - - setTimeout(() => { - console.log("Time's up! 10 seconds before the next game starts..."); - callback && callback(); - - // Schedule the next game in 10 seconds - setTimeout(() => { - infiniteTimerGame(callback); - }, 10000); - }, 1000); -} - -module.exports = infiniteTimerGame; -``` - -```javascript title="__tests__/infiniteTimerGame-test.js" -'use strict'; - -jest.useFakeTimers(); -jest.spyOn(global, 'setTimeout'); - -describe('infiniteTimerGame', () => { - test('schedules a 10-second timer after 1 second', () => { - const infiniteTimerGame = require('../infiniteTimerGame'); - const callback = jest.fn(); - - infiniteTimerGame(callback); - - // At this point in time, there should have been a single call to - // setTimeout to schedule the end of the game in 1 second. - expect(setTimeout).toHaveBeenCalledTimes(1); - expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 1000); - - // Fast forward and exhaust only currently pending timers - // (but not any new timers that get created during that process) - jest.runOnlyPendingTimers(); - - // At this point, our 1-second timer should have fired its callback - expect(callback).toBeCalled(); - - // And it should have created a new timer to start the game over in - // 10 seconds - expect(setTimeout).toHaveBeenCalledTimes(2); - expect(setTimeout).toHaveBeenLastCalledWith(expect.any(Function), 10000); - }); -}); -``` - -## Advance Timers by Time - -Another possibility is use `jest.advanceTimersByTime(msToRun)`. When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed. Additionally, if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue that should be run within msToRun milliseconds. - -```javascript title="timerGame.js" -'use strict'; - -function timerGame(callback) { - console.log('Ready....go!'); - setTimeout(() => { - console.log("Time's up -- stop!"); - callback && callback(); - }, 1000); -} - -module.exports = timerGame; -``` - -```javascript title="__tests__/timerGame-test.js" -jest.useFakeTimers(); -it('calls the callback after 1 second via advanceTimersByTime', () => { - const timerGame = require('../timerGame'); - const callback = jest.fn(); - - timerGame(callback); - - // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); - - // Fast-forward until all timers have been executed - jest.advanceTimersByTime(1000); - - // Now our callback should have been called! - expect(callback).toBeCalled(); - expect(callback).toHaveBeenCalledTimes(1); -}); -``` - -Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. - -The code for this example is available at [examples/timer](https://github.com/jestjs/jest/tree/main/examples/timer). diff --git a/website/versioned_docs/version-25.x/Troubleshooting.md b/website/versioned_docs/version-25.x/Troubleshooting.md deleted file mode 100644 index 5efe7e9efd24..000000000000 --- a/website/versioned_docs/version-25.x/Troubleshooting.md +++ /dev/null @@ -1,209 +0,0 @@ ---- -id: troubleshooting -title: Troubleshooting ---- - -Uh oh, something went wrong? Use this guide to resolve issues with Jest. - -## Tests are Failing and You Don't Know Why - -Try using the [debugging support](https://nodejs.org/api/debugger.html) built into Node. Place a `debugger;` statement in any of your tests, and then, in your project's directory, run: - -```bash -node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] -or on Windows -node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here] -``` - -This will run Jest in a Node process that an external debugger can connect to. Note that the process will pause until the debugger has connected to it. - -To debug in Google Chrome (or any Chromium-based browser), open your browser and go to `chrome://inspect` and click on "Open Dedicated DevTools for Node", which will give you a list of available node instances you can connect to. Click on the address displayed in the terminal (usually something like `localhost:9229`) after running the above command, and you will be able to debug Jest using Chrome's DevTools. - -The Chrome Developer Tools will be displayed, and a breakpoint will be set at the first line of the Jest CLI script (this is done to give you time to open the developer tools and to prevent Jest from executing before you have time to do so). Click the button that looks like a "play" button in the upper right hand side of the screen to continue execution. When Jest executes the test that contains the `debugger` statement, execution will pause and you can examine the current scope and call stack. - -:::note - -The `--runInBand` cli option makes sure Jest runs the test in the same process rather than spawning processes for individual tests. Normally Jest parallelizes test runs across processes but it is hard to debug many processes at the same time. - -::: - -## Debugging in VS Code - -There are multiple ways to debug Jest tests with [Visual Studio Code's](https://code.visualstudio.com) built-in [debugger](https://code.visualstudio.com/docs/nodejs/nodejs-debugging). - -To attach the built-in debugger, run your tests as aforementioned: - -```bash -node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] -or on Windows -node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other arguments here] -``` - -Then attach VS Code's debugger using the following `launch.json` config: - -```json -{ - "version": "0.2.0", - "configurations": [ - { - "type": "node", - "request": "attach", - "name": "Attach", - "port": 9229 - } - ] -} -``` - -To automatically launch and attach to a process running your tests, use the following configuration: - -```json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Debug Jest Tests", - "type": "node", - "request": "launch", - "runtimeArgs": [ - "--inspect-brk", - "${workspaceRoot}/node_modules/.bin/jest", - "--runInBand" - ], - "console": "integratedTerminal", - "internalConsoleOptions": "neverOpen" - } - ] -} -``` - -or the following for Windows: - -```json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Debug Jest Tests", - "type": "node", - "request": "launch", - "runtimeArgs": [ - "--inspect-brk", - "${workspaceRoot}/node_modules/jest/bin/jest.js", - "--runInBand" - ], - "console": "integratedTerminal", - "internalConsoleOptions": "neverOpen" - } - ] -} -``` - -If you are using Facebook's [`create-react-app`](https://github.com/facebookincubator/create-react-app), you can debug your Jest tests with the following configuration: - -```json -{ - "version": "0.2.0", - "configurations": [ - { - "name": "Debug CRA Tests", - "type": "node", - "request": "launch", - "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", - "args": [ - "test", - "--runInBand", - "--no-cache", - "--env=jsdom", - "--watchAll=false" - ], - "cwd": "${workspaceRoot}", - "console": "integratedTerminal", - "internalConsoleOptions": "neverOpen" - } - ] -} -``` - -More information on Node debugging can be found [here](https://nodejs.org/api/debugger.html). - -## Debugging in WebStorm - -[WebStorm](https://www.jetbrains.com/webstorm/) has built-in support for Jest. Read [Testing With Jest in WebStorm](https://blog.jetbrains.com/webstorm/2018/10/testing-with-jest-in-webstorm/) to learn more. - -## Caching Issues - -The transform script was changed or Babel was updated and the changes aren't being recognized by Jest? - -Retry with [`--no-cache`](CLI.md#--cache). Jest caches transformed module files to speed up test execution. If you are using your own custom transformer, consider adding a `getCacheKey` function to it: [getCacheKey in Relay](https://github.com/facebook/relay/blob/58cf36c73769690f0bbf90562707eadb062b029d/scripts/jest/preprocessor.js#L56-L61). - -## Unresolved Promises - -If a promise doesn't resolve at all, this error might be thrown: - -```bash -- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` -``` - -Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = jest.requireActual('promise');` and/or consolidate the used Promise libraries to a single one. - -If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` - -```js -jest.setTimeout(10000); // 10 second timeout -``` - -## Watchman Issues - -Try running Jest with [`--no-watchman`](CLI.md#--watchman) or set the `watchman` configuration option to `false`. - -Also see [watchman troubleshooting](https://facebook.github.io/watchman/docs/troubleshooting). - -## Tests are Extremely Slow on Docker and/or Continuous Integration (CI) server. - -While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/jestjs/jest/issues/1395) [discovered](https://github.com/jestjs/jest/issues/1524#issuecomment-260246008). - -Based on the [findings](https://github.com/jestjs/jest/issues/1524#issuecomment-262366820), one way to mitigate this issue and improve the speed by up to 50% is to run tests sequentially. - -In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#--runinband): - -```bash -# Using Jest CLI -jest --runInBand - -# Using yarn test (e.g. with create-react-app) -yarn test --runInBand -``` - -Another alternative to expediting test execution time on Continuous Integration Servers such as Travis-CI is to set the max worker pool to ~_4_. Specifically on Travis-CI, this can reduce test execution time in half. Note: The Travis CI _free_ plan available for open source projects only includes 2 CPU cores. - -```bash -# Using Jest CLI -jest --maxWorkers=4 - -# Using yarn test (e.g. with create-react-app) -yarn test --maxWorkers=4 -``` - -## `coveragePathIgnorePatterns` seems to not have any effect. - -Make sure you are not using the `babel-plugin-istanbul` plugin. Jest wraps Istanbul, and therefore also tells Istanbul what files to instrument with coverage collection. When using `babel-plugin-istanbul`, every file that is processed by Babel will have coverage collection code, hence it is not being ignored by `coveragePathIgnorePatterns`. - -## Defining Tests - -Tests must be defined synchronously for Jest to be able to collect your tests. - -As an example to show why this is the case, imagine we wrote a test like so: - -```js -// Don't do this it will not work -setTimeout(() => { - it('passes', () => expect(1).toBe(1)); -}, 0); -``` - -When Jest runs your test to collect the `test`s it will not find any because we have set the definition to happen asynchronously on the next tick of the event loop. This means when you are using `test.each` you cannot set the table asynchronously within a `beforeEach` / `beforeAll`. - -## Still unresolved? - -See [Help](/help). diff --git a/website/versioned_docs/version-25.x/TutorialAsync.md b/website/versioned_docs/version-25.x/TutorialAsync.md deleted file mode 100644 index d7f712fd9398..000000000000 --- a/website/versioned_docs/version-25.x/TutorialAsync.md +++ /dev/null @@ -1,161 +0,0 @@ ---- -id: tutorial-async -title: An Async Example ---- - -First, enable Babel support in Jest as documented in the [Getting Started](GettingStarted.md#using-babel) guide. - -Let's implement a module that fetches user data from an API and returns the user name. - -```js title="user.js" -import request from './request'; - -export function getUserName(userID) { - return request(`/users/${userID}`).then(user => user.name); -} -``` - -In the above implementation, we expect the `request.js` module to return a promise. We chain a call to `then` to receive the user name. - -Now imagine an implementation of `request.js` that goes to the network and fetches some user data: - -```js title="request.js" -const http = require('http'); - -export default function request(url) { - return new Promise(resolve => { - // This is an example of an http request, for example to fetch - // user data from an API. - // This module is being mocked in __mocks__/request.js - http.get({path: url}, response => { - let data = ''; - response.on('data', _data => (data += _data)); - response.on('end', () => resolve(data)); - }); - }); -} -``` - -Because we don't want to go to the network in our test, we are going to create a manual mock for our `request.js` module in the `__mocks__` folder (the folder is case-sensitive, `__MOCKS__` will not work). It could look something like this: - -```js title="__mocks__/request.js" -const users = { - 4: {name: 'Mark'}, - 5: {name: 'Paul'}, -}; - -export default function request(url) { - return new Promise((resolve, reject) => { - const userID = parseInt(url.substr('/users/'.length), 10); - process.nextTick(() => - users[userID] - ? resolve(users[userID]) - : reject({ - error: `User with ${userID} not found.`, - }), - ); - }); -} -``` - -Now let's write a test for our async functionality. - -```js title="__tests__/user-test.js" -jest.mock('../request'); - -import * as user from '../user'; - -// The assertion for a promise must be returned. -it('works with promises', () => { - expect.assertions(1); - return user.getUserName(4).then(data => expect(data).toBe('Mark')); -}); -``` - -We call `jest.mock('../request')` to tell Jest to use our manual mock. `it` expects the return value to be a Promise that is going to be resolved. You can chain as many Promises as you like and call `expect` at any time, as long as you return a Promise at the end. - -## `.resolves` - -There is a less verbose way using `resolves` to unwrap the value of a fulfilled promise together with any other matcher. If the promise is rejected, the assertion will fail. - -```js -it('works with resolves', () => { - expect.assertions(1); - return expect(user.getUserName(5)).resolves.toBe('Paul'); -}); -``` - -## `async`/`await` - -Writing tests using the `async`/`await` syntax is also possible. Here is how you'd write the same examples from before: - -```js -// async/await can be used. -it('works with async/await', async () => { - expect.assertions(1); - const data = await user.getUserName(4); - expect(data).toBe('Mark'); -}); - -// async/await can also be used with `.resolves`. -it('works with async/await and resolves', async () => { - expect.assertions(1); - await expect(user.getUserName(5)).resolves.toBe('Paul'); -}); -``` - -To enable async/await in your project, install [`@babel/preset-env`](https://babeljs.io/docs/en/babel-preset-env) and enable the feature in your `babel.config.js` file. - -## Error handling - -Errors can be handled using the `.catch` method. Make sure to add `expect.assertions` to verify that a certain number of assertions are called. Otherwise a fulfilled promise would not fail the test: - -```js -// Testing for async errors using Promise.catch. -it('tests error with promises', () => { - expect.assertions(1); - return user.getUserName(2).catch(e => - expect(e).toEqual({ - error: 'User with 2 not found.', - }), - ); -}); - -// Or using async/await. -it('tests error with async/await', async () => { - expect.assertions(1); - try { - await user.getUserName(1); - } catch (e) { - expect(e).toEqual({ - error: 'User with 1 not found.', - }); - } -}); -``` - -## `.rejects` - -The`.rejects` helper works like the `.resolves` helper. If the promise is fulfilled, the test will automatically fail. `expect.assertions(number)` is not required but recommended to verify that a certain number of [assertions](ExpectAPI.md#expectassertionsnumber) are called during a test. It is otherwise easy to forget to `return`/`await` the `.resolves` assertions. - -```js -// Testing for async errors using `.rejects`. -it('tests error with rejects', () => { - expect.assertions(1); - return expect(user.getUserName(3)).rejects.toEqual({ - error: 'User with 3 not found.', - }); -}); - -// Or using async/await with `.rejects`. -it('tests error with async/await and rejects', async () => { - expect.assertions(1); - await expect(user.getUserName(3)).rejects.toEqual({ - error: 'User with 3 not found.', - }); -}); -``` - -The code for this example is available at [examples/async](https://github.com/jestjs/jest/tree/main/examples/async). - -If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-25.x/TutorialReact.md b/website/versioned_docs/version-25.x/TutorialReact.md deleted file mode 100644 index 65cce15c0bbf..000000000000 --- a/website/versioned_docs/version-25.x/TutorialReact.md +++ /dev/null @@ -1,313 +0,0 @@ ---- -id: tutorial-react -title: Testing React Apps ---- - -At Facebook, we use Jest to test [React](https://reactjs.org/) applications. - -## Setup - -### Setup with Create React App - -If you are new to React, we recommend using [Create React App](https://create-react-app.dev/). It is ready to use and [ships with Jest](https://create-react-app.dev/docs/running-tests/#docsNav)! You will only need to add `react-test-renderer` for rendering snapshots. - -Run - -```bash -yarn add --dev react-test-renderer -``` - -### Setup without Create React App - -If you have an existing application you'll need to install a few packages to make everything work well together. We are using the `babel-jest` package and the `react` babel preset to transform our code inside of the test environment. Also see [using babel](GettingStarted.md#using-babel). - -Run - -```bash -yarn add --dev jest babel-jest @babel/preset-env @babel/preset-react react-test-renderer -``` - -Your `package.json` should look something like this (where `` is the actual latest version number for the package). Please add the scripts and jest configuration entries: - -```json - "dependencies": { - "react": "", - "react-dom": "" - }, - "devDependencies": { - "@babel/preset-env": "", - "@babel/preset-react": "", - "babel-jest": "", - "jest": "", - "react-test-renderer": "" - }, - "scripts": { - "test": "jest" - } -``` - -```js title="babel.config.js" -module.exports = { - presets: ['@babel/preset-env', '@babel/preset-react'], -}; -``` - -**And you're good to go!** - -### Snapshot Testing - -Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: - -```tsx title="Link.js" -import React, {useState} from 'react'; - -const STATUS = { - HOVERED: 'hovered', - NORMAL: 'normal', -}; - -const Link = ({page, children}) => { - const [status, setStatus] = useState(STATUS.NORMAL); - - const onMouseEnter = () => { - setStatus(STATUS.HOVERED); - }; - - const onMouseLeave = () => { - setStatus(STATUS.NORMAL); - }; - - return ( - - {children} - - ); -}; - -export default Link; -``` - -:::note - -Examples are using Function components, but Class components can be tested in the same way. See [React: Function and Class Components](https://reactjs.org/docs/components-and-props.html#function-and-class-components). **Reminders** that with Class components, we expect Jest to be used to test props and not methods directly. - -::: - -Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file: - -```tsx title="Link.test.js" -import React from 'react'; -import renderer from 'react-test-renderer'; -import Link from '../Link'; - -test('Link changes the class when hovered', () => { - const component = renderer.create( - Facebook, - ); - let tree = component.toJSON(); - expect(tree).toMatchSnapshot(); - - // manually trigger the callback - tree.props.onMouseEnter(); - // re-rendering - tree = component.toJSON(); - expect(tree).toMatchSnapshot(); - - // manually trigger the callback - tree.props.onMouseLeave(); - // re-rendering - tree = component.toJSON(); - expect(tree).toMatchSnapshot(); -}); -``` - -When you run `yarn test` or `jest`, this will produce an output file like this: - -```javascript title="__tests__/__snapshots__/Link.test.js.snap" -exports[`Link changes the class when hovered 1`] = ` - - Facebook - -`; - -exports[`Link changes the class when hovered 2`] = ` - - Facebook - -`; - -exports[`Link changes the class when hovered 3`] = ` - - Facebook - -`; -``` - -The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. - -The code for this example is available at [examples/snapshot](https://github.com/jestjs/jest/tree/main/examples/snapshot). - -#### Snapshot Testing with Mocks, Enzyme and React 16 - -There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style: - -```js -jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent'); -``` - -Then you will see warnings in the console: - -```bash -Warning: is using uppercase HTML. Always use lowercase HTML tags in React. - -# Or: -Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. -``` - -React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are: - -1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward: - ```js - jest.mock('./SomeComponent', () => () => 'SomeComponent'); - ``` -2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name. - ```tsx - jest.mock('./Widget', () => () => ); - ``` -3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme. -4. Disable warnings all together (should be done in your jest setup file): - ```js - jest.mock('fbjs/lib/warning', () => require('fbjs/lib/emptyFunction')); - ``` - This shouldn't normally be your option of choice as useful warnings could be lost. However, in some cases, for example when testing react-native's components we are rendering react-native tags into the DOM and many warnings are irrelevant. Another option is to swizzle the console.warn and suppress specific warnings. - -### DOM Testing - -If you'd like to assert, and manipulate your rendered components you can use [react-testing-library](https://github.com/testing-library/react-testing-library), [Enzyme](https://enzymejs.github.io/enzyme/), or React's [TestUtils](https://reactjs.org/docs/test-utils.html). The following two examples use react-testing-library and Enzyme. - -#### react-testing-library - -You have to run `yarn add --dev @testing-library/react` to use react-testing-library. - -Let's implement a checkbox which swaps between two labels: - -```tsx title="CheckboxWithLabel.js" -import React, {useState} from 'react'; - -const CheckboxWithLabel = ({labelOn, labelOff}) => { - const [isChecked, setIsChecked] = useState(false); - - const onChange = () => { - setIsChecked(!isChecked); - }; - - return ( - - ); -}; - -export default CheckboxWithLabel; -``` - -```tsx title="__tests__/CheckboxWithLabel-test.js" -import React from 'react'; -import {cleanup, fireEvent, render} from '@testing-library/react'; -import CheckboxWithLabel from '../CheckboxWithLabel'; - -// Note: running cleanup afterEach is done automatically for you in @testing-library/react@9.0.0 or higher -// unmount and cleanup DOM after the test is finished. -afterEach(cleanup); - -it('CheckboxWithLabel changes the text after click', () => { - const {queryByLabelText, getByLabelText} = render( - , - ); - - expect(queryByLabelText(/off/i)).toBeTruthy(); - - fireEvent.click(getByLabelText(/off/i)); - - expect(queryByLabelText(/on/i)).toBeTruthy(); -}); -``` - -The code for this example is available at [examples/react-testing-library](https://github.com/jestjs/jest/tree/main/examples/react-testing-library). - -#### Enzyme - -You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React version below 15.5.0, you will also need to install `react-addons-test-utils`. - -Let's rewrite the test from above using Enzyme instead of react-testing-library. We use Enzyme's [shallow renderer](https://enzymejs.github.io/enzyme/docs/api/shallow.html) in this example. - -```tsx title="__tests__/CheckboxWithLabel-test.js" -import React from 'react'; -import {shallow} from 'enzyme'; -import CheckboxWithLabel from '../CheckboxWithLabel'; - -test('CheckboxWithLabel changes the text after click', () => { - // Render a checkbox with label in the document - const checkbox = shallow(); - - expect(checkbox.text()).toBe('Off'); - - checkbox.find('input').simulate('change'); - - expect(checkbox.text()).toBe('On'); -}); -``` - -### Custom transformers - -If you need more advanced functionality, you can also build your own transformer. Instead of using `babel-jest`, here is an example of using `@babel/core`: - -```javascript title="custom-transformer.js" -'use strict'; - -const {transform} = require('@babel/core'); -const jestPreset = require('babel-preset-jest'); - -module.exports = { - process(src, filename) { - const result = transform(src, { - filename, - presets: [jestPreset], - }); - - return result || src; - }, -}; -``` - -Don't forget to install the `@babel/core` and `babel-preset-jest` packages for this example to work. - -To make this work with Jest you need to update your Jest configuration with this: `"transform": {"\\.js$": "path/to/custom-transformer.js"}`. - -If you'd like to build a transformer with babel support, you can also use `babel-jest` to compose one and pass in your custom configuration options: - -```javascript -const babelJest = require('babel-jest'); - -module.exports = babelJest.createTransformer({ - presets: ['my-custom-preset'], -}); -``` diff --git a/website/versioned_docs/version-25.x/TutorialReactNative.md b/website/versioned_docs/version-25.x/TutorialReactNative.md deleted file mode 100644 index 8804c38a1b20..000000000000 --- a/website/versioned_docs/version-25.x/TutorialReactNative.md +++ /dev/null @@ -1,219 +0,0 @@ ---- -id: tutorial-react-native -title: Testing React Native Apps ---- - -At Facebook, we use Jest to test [React Native](https://reactnative.dev/) applications. - -Get a deeper insight into testing a working React Native app example by reading the following series: [Part 1: Jest – Snapshot come into play](https://callstack.com/blog/testing-react-native-with-the-new-jest-part-1-snapshots-come-into-play/) and [Part 2: Jest – Redux Snapshots for your Actions and Reducers](https://callstack.com/blog/testing-react-native-with-the-new-jest-part-2-redux-snapshots-for-your-actions-and-reducers/). - -## Setup - -Starting from react-native version 0.38, a Jest setup is included by default when running `react-native init`. The following configuration should be automatically added to your package.json file: - -```json -{ - "scripts": { - "test": "jest" - }, - "jest": { - "preset": "react-native" - } -} -``` - -Run `yarn test` to run tests with Jest. - -:::tip - -If you are upgrading your react-native application and previously used the `jest-react-native` preset, remove the dependency from your `package.json` file and change the preset to `react-native` instead.\_ - -::: - -## Snapshot Test - -Let's create a [snapshot test](SnapshotTesting.md) for a small intro component with a few views and text components and some styles: - -```tsx title="Intro.js" -import React, {Component} from 'react'; -import {StyleSheet, Text, View} from 'react-native'; - -class Intro extends Component { - render() { - return ( - - Welcome to React Native! - - This is a React Native snapshot test. - - - ); - } -} - -const styles = StyleSheet.create({ - container: { - alignItems: 'center', - backgroundColor: '#F5FCFF', - flex: 1, - justifyContent: 'center', - }, - instructions: { - color: '#333333', - marginBottom: 5, - textAlign: 'center', - }, - welcome: { - fontSize: 20, - margin: 10, - textAlign: 'center', - }, -}); - -export default Intro; -``` - -Now let's use React's test renderer and Jest's snapshot feature to interact with the component and capture the rendered output and create a snapshot file: - -```tsx title="__tests__/Intro-test.js" -import React from 'react'; -import renderer from 'react-test-renderer'; -import Intro from '../Intro'; - -test('renders correctly', () => { - const tree = renderer.create().toJSON(); - expect(tree).toMatchSnapshot(); -}); -``` - -When you run `yarn test` or `jest`, this will produce an output file like this: - -```javascript title="__tests__/__snapshots__/Intro-test.js.snap" -exports[`Intro renders correctly 1`] = ` - - - Welcome to React Native! - - - This is a React Native snapshot test. - - -`; -``` - -The next time you run the tests, the rendered output will be compared to the previously created snapshot. The snapshot should be committed along with code changes. When a snapshot test fails, you need to inspect whether it is an intended or unintended change. If the change is expected you can invoke Jest with `jest -u` to overwrite the existing snapshot. - -The code for this example is available at [examples/react-native](https://github.com/jestjs/jest/tree/main/examples/react-native). - -## Preset configuration - -The preset sets up the environment and is very opinionated and based on what we found to be useful at Facebook. All of the configuration options can be overwritten just as they can be customized when no preset is used. - -### Environment - -`react-native` ships with a Jest preset, so the `jest.preset` field of your `package.json` should point to `react-native`. The preset is a node environment that mimics the environment of a React Native app. Because it doesn't load any DOM or browser APIs, it greatly improves Jest's startup time. - -### transformIgnorePatterns customization - -The [`transformIgnorePatterns`](configuration#transformignorepatterns-arraystring) option can be used to specify which files shall be transformed by Babel. Many `react-native` npm modules unfortunately don't pre-compile their source code before publishing. - -By default the `jest-react-native` preset only processes the project's own source files and `react-native`. If you have npm dependencies that have to be transformed you can customize this configuration option by including modules other than `react-native` by grouping them and separating them with the `|` operator: - -```json -{ - "transformIgnorePatterns": [ - "node_modules/(?!(react-native|my-project|react-native-button)/)" - ] -} -``` - -You can test which paths would match (and thus be excluded from transformation) with a tool [like this](https://regex101.com/r/JsLIDM/1). - -`transformIgnorePatterns` will exclude a file from transformation if the path matches against **any** pattern provided. Splitting into multiple patterns could therefore have unintended results if you are not careful. In the example below, the exclusion (also known as a negative lookahead assertion) for `foo` and `bar` cancel each other out: - -```json -{ - "transformIgnorePatterns": ["node_modules/(?!foo/)", "node_modules/(?!bar/)"] // not what you want -} -``` - -### setupFiles - -If you'd like to provide additional configuration for every test file, the [`setupFiles` configuration option](configuration#setupfiles-array) can be used to specify setup scripts. - -### moduleNameMapper - -The [`moduleNameMapper`](configuration#modulenamemapper-objectstring-string--arraystring) can be used to map a module path to a different module. By default the preset maps all images to an image stub module but if a module cannot be found this configuration option can help: - -```json -{ - "moduleNameMapper": { - "my-module.js": "/path/to/my-module.js" - } -} -``` - -## Tips - -### Mock native modules using jest.mock - -The Jest preset built into `react-native` comes with a few default mocks that are applied on a react-native repository. However, some react-native components or third party components rely on native code to be rendered. In such cases, Jest's manual mocking system can help to mock out the underlying implementation. - -For example, if your code depends on a third party native video component called `react-native-video` you might want to stub it out with a manual mock like this: - -```js -jest.mock('react-native-video', () => 'Video'); -``` - -This will render the component as `