diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index c326408ebd5a..98bbca702d84 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -3,6 +3,7 @@ THIS IS NOT A HELP FORUM. If you are experiencing problems with setting up Jest, please make sure to visit our Help page: https://facebook.github.io/jest/help.html --> + -**Do you want to request a *feature* or report a *bug*?** +**Do you want to request a _feature_ or report a _bug_?** **What is the current behavior?** -**If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can `yarn install` and `yarn test`.** +**If the current behavior is a bug, please provide the steps to reproduce and +either a repl.it demo through https://repl.it/languages/jest or a minimal +repository on GitHub that we can `yarn install` and `yarn test`.** **What is the expected behavior?** -**Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.** +**Please provide your exact Jest configuration and mention your Jest, node, +yarn/npm version and operating system.** diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e9f45620e5f7..506f04bbdfe2 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,4 +1,5 @@ + **Summary** diff --git a/.vscode/settings.json b/.vscode/settings.json index d0188f92d5cb..c4951686b125 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -9,10 +9,5 @@ "flow.useNPMPackagedFlow": true, "javascript.validate.enable": false, "jest.pathToJest": "yarn jest --", - "prettier.eslintIntegration": true, - "prettier.parser": "flow", - "prettier.printWidth": 80, - "prettier.semi": true, - "prettier.singleQuote": true, - "prettier.trailingComma": "all" + "prettier.eslintIntegration": true } diff --git a/CHANGELOG.md b/CHANGELOG.md index dbcf90f41a8b..abc4bd929f62 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,102 +1,188 @@ ## master ### Fixes -* `[jest-docblock]` pragmas should preserve urls ([#4837](https://github.com/facebook/jest/pull/4629)) -* `[jest-cli]` Check if `npm_lifecycle_script` calls Jest directly ([#4629](https://github.com/facebook/jest/pull/4629)) -* `[jest-cli]` Fix --showConfig to show all configs ([#4494](https://github.com/facebook/jest/pull/4494)) -* `[jest-cli]` Throw if `maxWorkers` doesn't have a value ([#4591](https://github.com/facebook/jest/pull/4591)) -* `[jest-config]` Fix `--passWithNoTests` ([#4639](https://github.com/facebook/jest/pull/4639)) -* `[jest-config]` Support `rootDir` tag in testEnvironment ([#4579](https://github.com/facebook/jest/pull/4579)) -* `[jest-editor-support]` Fix `--showConfig` to support jest 20 and jest 21 ([#4575](https://github.com/facebook/jest/pull/4575)) -* `[jest-editor-support]` Fix editor support test for node 4 ([#4640](https://github.com/facebook/jest/pull/4640)) -* `[jest-mock]` Support mocking constructor in `mockImplementationOnce` ([#4599](https://github.com/facebook/jest/pull/4599)) -* `[jest-runtime]` Fix manual user mocks not working with custom resolver ([#4489](https://github.com/facebook/jest/pull/4489)) -* `[jest-runtime]` Move `babel-core` to peer dependencies so it works with Babel 7 ([#4557](https://github.com/facebook/jest/pull/4557)) -* `[jest-util]` Fix `runOnlyPendingTimers` for `setTimeout` inside `setImmediate` ([#4608](https://github.com/facebook/jest/pull/4608)) -* `[jest-message-util]` Always remove node internals from stacktraces ([#4695](https://github.com/facebook/jest/pull/4695)) -* `[jest-resolve]` changes method of determining builtin modules to include missing builtins ([#4740](https://github.com/facebook/jest/pull/4740)) -* `[pretty-format]` Prevent error in pretty-format for window in jsdom test env ([#4750](https://github.com/facebook/jest/pull/4750)) -* `[jest-resolve]` Preserve module identity for symlinks ([#4761](https://github.com/facebook/jest/pull/4761)) -* `[jest-config]` Include error message for `preset` json ([#4766](https://github.com/facebook/jest/pull/4766)) -* `[pretty-format]` Throw `PrettyFormatPluginError` if a plugin halts with an exception ([#4787](https://github.com/facebook/jest/pull/4787)) -* `[expect]` Keep the stack trace unchanged when `PrettyFormatPluginError` is thrown by pretty-format ([#4787](https://github.com/facebook/jest/pull/4787)) -* `[jest-environment-jsdom]` Fix asynchronous test will fail due to timeout issue. ([#4669](https://github.com/facebook/jest/pull/4669)) + +* `[jest-docblock]` pragmas should preserve urls + ([#4837](https://github.com/facebook/jest/pull/4629)) +* `[jest-cli]` Check if `npm_lifecycle_script` calls Jest directly + ([#4629](https://github.com/facebook/jest/pull/4629)) +* `[jest-cli]` Fix --showConfig to show all configs + ([#4494](https://github.com/facebook/jest/pull/4494)) +* `[jest-cli]` Throw if `maxWorkers` doesn't have a value + ([#4591](https://github.com/facebook/jest/pull/4591)) +* `[jest-config]` Fix `--passWithNoTests` + ([#4639](https://github.com/facebook/jest/pull/4639)) +* `[jest-config]` Support `rootDir` tag in testEnvironment + ([#4579](https://github.com/facebook/jest/pull/4579)) +* `[jest-editor-support]` Fix `--showConfig` to support jest 20 and jest 21 + ([#4575](https://github.com/facebook/jest/pull/4575)) +* `[jest-editor-support]` Fix editor support test for node 4 + ([#4640](https://github.com/facebook/jest/pull/4640)) +* `[jest-mock]` Support mocking constructor in `mockImplementationOnce` + ([#4599](https://github.com/facebook/jest/pull/4599)) +* `[jest-runtime]` Fix manual user mocks not working with custom resolver + ([#4489](https://github.com/facebook/jest/pull/4489)) +* `[jest-runtime]` Move `babel-core` to peer dependencies so it works with Babel + 7 ([#4557](https://github.com/facebook/jest/pull/4557)) +* `[jest-util]` Fix `runOnlyPendingTimers` for `setTimeout` inside + `setImmediate` ([#4608](https://github.com/facebook/jest/pull/4608)) +* `[jest-message-util]` Always remove node internals from stacktraces + ([#4695](https://github.com/facebook/jest/pull/4695)) +* `[jest-resolve]` changes method of determining builtin modules to include + missing builtins ([#4740](https://github.com/facebook/jest/pull/4740)) +* `[pretty-format]` Prevent error in pretty-format for window in jsdom test env + ([#4750](https://github.com/facebook/jest/pull/4750)) +* `[jest-resolve]` Preserve module identity for symlinks + ([#4761](https://github.com/facebook/jest/pull/4761)) +* `[jest-config]` Include error message for `preset` json + ([#4766](https://github.com/facebook/jest/pull/4766)) +* `[pretty-format]` Throw `PrettyFormatPluginError` if a plugin halts with an + exception ([#4787](https://github.com/facebook/jest/pull/4787)) +* `[expect]` Keep the stack trace unchanged when `PrettyFormatPluginError` is + thrown by pretty-format ([#4787](https://github.com/facebook/jest/pull/4787)) +* `[jest-environment-jsdom]` Fix asynchronous test will fail due to timeout + issue. ([#4669](https://github.com/facebook/jest/pull/4669)) ### Features -* `[jest-mock]` Add `timestamps` to mock state. ([#4866](https://github.com/facebook/jest/pull/4866)) -* `[eslint-plugin-jest]` Add `prefer-to-have-length` lint rule. ([#4771](https://github.com/facebook/jest/pull/4771)) -* `[jest-environment-jsdom]` [**BREAKING**] Upgrade to JSDOM@11 ([#4770](https://github.com/facebook/jest/pull/4770)) -* `[jest-environment-*]` [**BREAKING**] Add Async Test Environment APIs, dispose is now teardown ([#4506](https://github.com/facebook/jest/pull/4506)) -* `[jest-cli]` Add an option to clear the cache ([#4430](https://github.com/facebook/jest/pull/4430)) -* `[babel-plugin-jest-hoist]` Improve error message, that the second argument of `jest.mock` must be an inline function ([#4593](https://github.com/facebook/jest/pull/4593)) -* `[jest-snapshot]` [**BREAKING**] Concatenate name of test and snapshot ([#4460](https://github.com/facebook/jest/pull/4460)) -* `[jest-cli]` Add an option to fail if no tests are found ([#3672](https://github.com/facebook/jest/pull/3672)) -* `[jest-diff]` Highlight only last of odd length leading spaces ([#4558](https://github.com/facebook/jest/pull/4558)) -* `[jest-docblock]` Add `docblock.print()` ([#4517](https://github.com/facebook/jest/pull/4517)) -* `[jest-docblock]` Add `strip` ([#4571](https://github.com/facebook/jest/pull/4571)) -* `[jest-docblock]` Preserve leading whitespace in docblock comments ([#4576](https://github.com/facebook/jest/pull/4576)) -* `[jest-docblock]` remove leading newlines from `parswWithComments().comments` ([#4610](https://github.com/facebook/jest/pull/4610)) -* `[jest-editor-support]` Add Snapshots metadata ([#4570](https://github.com/facebook/jest/pull/4570)) -* `[jest-editor-support]` Adds an 'any' to the typedef for `updateFileWithJestStatus` ([#4636](https://github.com/facebook/jest/pull/4636)) -* `[jest-editor-support]` Better monorepo support ([#4572](https://github.com/facebook/jest/pull/4572)) -* `[jest-environment-jsdom]` Add simple rAF polyfill in jsdom environment to work with React 16 ([#4568](https://github.com/facebook/jest/pull/4568)) -* `[jest-environment-node]` Implement node Timer api ([#4622](https://github.com/facebook/jest/pull/4622)) -* `[jest-jasmine2]` Add testPath to reporter callbacks ([#4594](https://github.com/facebook/jest/pull/4594)) -* `[jest-mock]` Added support for naming mocked functions with `.mockName(value)` and `.mockGetName()` ([#4586](https://github.com/facebook/jest/pull/4586)) -* `[jest-runtime]` Add `module.loaded`, and make `module.require` not enumerable ([#4623](https://github.com/facebook/jest/pull/4623)) -* `[jest-runtime]` Add `module.parent` ([#4614](https://github.com/facebook/jest/pull/4614)) -* `[jest-runtime]` Support sourcemaps in transformers ([#3458](https://github.com/facebook/jest/pull/3458)) -* `[jest-snapshot]` [**BREAKING**] Add a serializer for `jest.fn` to allow a snapshot of a jest mock ([#4668](https://github.com/facebook/jest/pull/4668)) -* `[jest-worker]` Initial version of parallel worker abstraction, say hello! ([#4497](https://github.com/facebook/jest/pull/4497)) -* `[jest-jasmine2]` Add `testLocationInResults` flag to add location information per spec to test results ([#4782](https://github.com/facebook/jest/pull/4782)) + +* `[jest-mock]` Add `timestamps` to mock state. + ([#4866](https://github.com/facebook/jest/pull/4866)) +* `[eslint-plugin-jest]` Add `prefer-to-have-length` lint rule. + ([#4771](https://github.com/facebook/jest/pull/4771)) +* `[jest-environment-jsdom]` [**BREAKING**] Upgrade to JSDOM@11 + ([#4770](https://github.com/facebook/jest/pull/4770)) +* `[jest-environment-*]` [**BREAKING**] Add Async Test Environment APIs, dispose + is now teardown ([#4506](https://github.com/facebook/jest/pull/4506)) +* `[jest-cli]` Add an option to clear the cache + ([#4430](https://github.com/facebook/jest/pull/4430)) +* `[babel-plugin-jest-hoist]` Improve error message, that the second argument of + `jest.mock` must be an inline function + ([#4593](https://github.com/facebook/jest/pull/4593)) +* `[jest-snapshot]` [**BREAKING**] Concatenate name of test and snapshot + ([#4460](https://github.com/facebook/jest/pull/4460)) +* `[jest-cli]` Add an option to fail if no tests are found + ([#3672](https://github.com/facebook/jest/pull/3672)) +* `[jest-diff]` Highlight only last of odd length leading spaces + ([#4558](https://github.com/facebook/jest/pull/4558)) +* `[jest-docblock]` Add `docblock.print()` + ([#4517](https://github.com/facebook/jest/pull/4517)) +* `[jest-docblock]` Add `strip` + ([#4571](https://github.com/facebook/jest/pull/4571)) +* `[jest-docblock]` Preserve leading whitespace in docblock comments + ([#4576](https://github.com/facebook/jest/pull/4576)) +* `[jest-docblock]` remove leading newlines from `parswWithComments().comments` + ([#4610](https://github.com/facebook/jest/pull/4610)) +* `[jest-editor-support]` Add Snapshots metadata + ([#4570](https://github.com/facebook/jest/pull/4570)) +* `[jest-editor-support]` Adds an 'any' to the typedef for + `updateFileWithJestStatus` + ([#4636](https://github.com/facebook/jest/pull/4636)) +* `[jest-editor-support]` Better monorepo support + ([#4572](https://github.com/facebook/jest/pull/4572)) +* `[jest-environment-jsdom]` Add simple rAF polyfill in jsdom environment to + work with React 16 ([#4568](https://github.com/facebook/jest/pull/4568)) +* `[jest-environment-node]` Implement node Timer api + ([#4622](https://github.com/facebook/jest/pull/4622)) +* `[jest-jasmine2]` Add testPath to reporter callbacks + ([#4594](https://github.com/facebook/jest/pull/4594)) +* `[jest-mock]` Added support for naming mocked functions with + `.mockName(value)` and `.mockGetName()` + ([#4586](https://github.com/facebook/jest/pull/4586)) +* `[jest-runtime]` Add `module.loaded`, and make `module.require` not enumerable + ([#4623](https://github.com/facebook/jest/pull/4623)) +* `[jest-runtime]` Add `module.parent` + ([#4614](https://github.com/facebook/jest/pull/4614)) +* `[jest-runtime]` Support sourcemaps in transformers + ([#3458](https://github.com/facebook/jest/pull/3458)) +* `[jest-snapshot]` [**BREAKING**] Add a serializer for `jest.fn` to allow a + snapshot of a jest mock ([#4668](https://github.com/facebook/jest/pull/4668)) +* `[jest-worker]` Initial version of parallel worker abstraction, say hello! + ([#4497](https://github.com/facebook/jest/pull/4497)) +* `[jest-jasmine2]` Add `testLocationInResults` flag to add location information + per spec to test results ([#4782](https://github.com/facebook/jest/pull/4782)) ### Chore & Maintenance -* `[*]` [**BREAKING**] Drop support for Node.js version 4 ([#4769](https://github.com/facebook/jest/pull/4769)) -* `[eslint-plugin-jest]` Removed from the Jest core repo, and moved to https://github.com/jest-community/eslint-plugin-jest ([#4867](https://github.com/facebook/jest/pull/4867)) -* `[babel-jest]` Explicitly bump istanbul to newer versions ([#4616](https://github.com/facebook/jest/pull/4616)) -* `[expect]` Upgrade mocha and rollup for browser testing ([#4642](https://github.com/facebook/jest/pull/4642)) -* `[docs]` Add info about `coveragePathIgnorePatterns` ([#4602](https://github.com/facebook/jest/pull/4602)) -* `[docs]` Add Vuejs series of testing with Jest ([#4648](https://github.com/facebook/jest/pull/4648)) -* `[docs]` Mention about optional `done` argument in test function ([#4556](https://github.com/facebook/jest/pull/4556)) -* `[jest-cli]` Bump node-notifier version ([#4609](https://github.com/facebook/jest/pull/4609)) -* `[jest-diff]` Simplify highlight for leading and trailing spaces ([#4553](https://github.com/facebook/jest/pull/4553)) -* `[jest-get-type]` Add support for date ([#4621](https://github.com/facebook/jest/pull/4621)) -* `[jest-matcher-utils]` Call `chalk.inverse` for trailing spaces ([#4578](https://github.com/facebook/jest/pull/4578)) -* `[jest-runtime]` Add `.advanceTimersByTime`; keep `.runTimersToTime()` as an alias. + +* `[*]` [**BREAKING**] Drop support for Node.js version 4 + ([#4769](https://github.com/facebook/jest/pull/4769)) +* `[eslint-plugin-jest]` Removed from the Jest core repo, and moved to + https://github.com/jest-community/eslint-plugin-jest + ([#4867](https://github.com/facebook/jest/pull/4867)) +* `[babel-jest]` Explicitly bump istanbul to newer versions + ([#4616](https://github.com/facebook/jest/pull/4616)) +* `[expect]` Upgrade mocha and rollup for browser testing + ([#4642](https://github.com/facebook/jest/pull/4642)) +* `[docs]` Add info about `coveragePathIgnorePatterns` + ([#4602](https://github.com/facebook/jest/pull/4602)) +* `[docs]` Add Vuejs series of testing with Jest + ([#4648](https://github.com/facebook/jest/pull/4648)) +* `[docs]` Mention about optional `done` argument in test function + ([#4556](https://github.com/facebook/jest/pull/4556)) +* `[jest-cli]` Bump node-notifier version + ([#4609](https://github.com/facebook/jest/pull/4609)) +* `[jest-diff]` Simplify highlight for leading and trailing spaces + ([#4553](https://github.com/facebook/jest/pull/4553)) +* `[jest-get-type]` Add support for date + ([#4621](https://github.com/facebook/jest/pull/4621)) +* `[jest-matcher-utils]` Call `chalk.inverse` for trailing spaces + ([#4578](https://github.com/facebook/jest/pull/4578)) +* `[jest-runtime]` Add `.advanceTimersByTime`; keep `.runTimersToTime()` as an + alias. ## jest 21.2.1 -* Fix watchAll not running tests on save ([#4550](https://github.com/facebook/jest/pull/4550)) -* Add missing escape sequences to ConvertAnsi plugin ([#4544](https://github.com/facebook/jest/pull/4544)) +* Fix watchAll not running tests on save + ([#4550](https://github.com/facebook/jest/pull/4550)) +* Add missing escape sequences to ConvertAnsi plugin + ([#4544](https://github.com/facebook/jest/pull/4544)) ## jest 21.2.0 * 🃏 Change license from BSD+Patents to MIT. -* Allow eslint-plugin to recognize more disabled tests ([#4533](https://github.com/facebook/jest/pull/4533)) -* Add babel-plugin for object spread syntax to babel-preset-jest ([#4519](https://github.com/facebook/jest/pull/4519)) -* Display outer element and trailing newline consistently in jest-diff ([#4520](https://github.com/facebook/jest/pull/4520)) -* Do not modify stack trace of JestAssertionError ([#4516](https://github.com/facebook/jest/pull/4516)) -* Print errors after test structure in verbose mode ([#4504](https://github.com/facebook/jest/pull/4504)) -* Fix `--silent --verbose` problem ([#4505](https://github.com/facebook/jest/pull/4505)) -* Fix: Reset local state of assertions when using hasAssertions ([#4498](https://github.com/facebook/jest/pull/4498)) -* jest-resolve: Prevent default resolver failure when potential resolution directory does not exist ([#4483](https://github.com/facebook/jest/pull/4483)) +* Allow eslint-plugin to recognize more disabled tests + ([#4533](https://github.com/facebook/jest/pull/4533)) +* Add babel-plugin for object spread syntax to babel-preset-jest + ([#4519](https://github.com/facebook/jest/pull/4519)) +* Display outer element and trailing newline consistently in jest-diff + ([#4520](https://github.com/facebook/jest/pull/4520)) +* Do not modify stack trace of JestAssertionError + ([#4516](https://github.com/facebook/jest/pull/4516)) +* Print errors after test structure in verbose mode + ([#4504](https://github.com/facebook/jest/pull/4504)) +* Fix `--silent --verbose` problem + ([#4505](https://github.com/facebook/jest/pull/4505)) +* Fix: Reset local state of assertions when using hasAssertions + ([#4498](https://github.com/facebook/jest/pull/4498)) +* jest-resolve: Prevent default resolver failure when potential resolution + directory does not exist ([#4483](https://github.com/facebook/jest/pull/4483)) ## jest 21.1.0 -* (minor) Use ES module exports ([#4454](https://github.com/facebook/jest/pull/4454)) -* Allow chaining mockClear and mockReset ([#4475](https://github.com/facebook/jest/pull/4475)) -* Call jest-diff and pretty-format more precisely in toHaveProperty matcher ([#4445](https://github.com/facebook/jest/pull/4445)) -* Expose restoreAllMocks to object ([#4463](https://github.com/facebook/jest/pull/4463)) -* Fix function name cleaning when making mock fn ([#4464](https://github.com/facebook/jest/pull/4464)) -* Fix Map/Set equality checker ([#4404](https://github.com/facebook/jest/pull/4404)) -* Make FUNCTION_NAME_RESERVED_PATTERN stateless ([#4466](https://github.com/facebook/jest/pull/4466)) +* (minor) Use ES module exports + ([#4454](https://github.com/facebook/jest/pull/4454)) +* Allow chaining mockClear and mockReset + ([#4475](https://github.com/facebook/jest/pull/4475)) +* Call jest-diff and pretty-format more precisely in toHaveProperty matcher + ([#4445](https://github.com/facebook/jest/pull/4445)) +* Expose restoreAllMocks to object + ([#4463](https://github.com/facebook/jest/pull/4463)) +* Fix function name cleaning when making mock fn + ([#4464](https://github.com/facebook/jest/pull/4464)) +* Fix Map/Set equality checker + ([#4404](https://github.com/facebook/jest/pull/4404)) +* Make FUNCTION_NAME_RESERVED_PATTERN stateless + ([#4466](https://github.com/facebook/jest/pull/4466)) ## jest 21.0.2 -* Take precedence of NODE_PATH when resolving node_modules directories ([#4453](https://github.com/facebook/jest/pull/4453)) -* Fix race condition with --coverage and babel-jest identical file contents edge case ([#4432](https://github.com/facebook/jest/pull/4432)) -* Add extra parameter `--runTestsByPath`. ([#4411](https://github.com/facebook/jest/pull/4411)) -* Upgrade all outdated deps ([#4425](https://github.com/facebook/jest/pull/4425)) +* Take precedence of NODE_PATH when resolving node_modules directories + ([#4453](https://github.com/facebook/jest/pull/4453)) +* Fix race condition with --coverage and babel-jest identical file contents edge + case ([#4432](https://github.com/facebook/jest/pull/4432)) +* Add extra parameter `--runTestsByPath`. + ([#4411](https://github.com/facebook/jest/pull/4411)) +* Upgrade all outdated deps + ([#4425](https://github.com/facebook/jest/pull/4425)) ## jest 21.0.1 @@ -104,275 +190,502 @@ ## jest 21.0.0 -* Add --changedFilesWithAncestor ([#4070](https://github.com/facebook/jest/pull/4070)) +* Add --changedFilesWithAncestor + ([#4070](https://github.com/facebook/jest/pull/4070)) * Add --findRelatedFiles ([#4131](https://github.com/facebook/jest/pull/4131)) * Add --onlyChanged tests ([#3977](https://github.com/facebook/jest/pull/3977)) -* Add `contextLines` option to jest-diff ([#4152](https://github.com/facebook/jest/pull/4152)) -* Add alternative serialize API for pretty-format plugins ([#4114](https://github.com/facebook/jest/pull/4114)) +* Add `contextLines` option to jest-diff + ([#4152](https://github.com/facebook/jest/pull/4152)) +* Add alternative serialize API for pretty-format plugins + ([#4114](https://github.com/facebook/jest/pull/4114)) * Add displayName to MPR ([#4327](https://github.com/facebook/jest/pull/4327)) -* Add displayName to TestResult ([#4408](https://github.com/facebook/jest/pull/4408)) -* Add es5 build of pretty-format ([#4075](https://github.com/facebook/jest/pull/4075)) -* Add extra info to no tests for changed files message ([#4188](https://github.com/facebook/jest/pull/4188)) -* Add fake chalk in browser builds in order to support IE10 ([#4367](https://github.com/facebook/jest/pull/4367)) +* Add displayName to TestResult + ([#4408](https://github.com/facebook/jest/pull/4408)) +* Add es5 build of pretty-format + ([#4075](https://github.com/facebook/jest/pull/4075)) +* Add extra info to no tests for changed files message + ([#4188](https://github.com/facebook/jest/pull/4188)) +* Add fake chalk in browser builds in order to support IE10 + ([#4367](https://github.com/facebook/jest/pull/4367)) * Add jest.requireActual ([#4260](https://github.com/facebook/jest/pull/4260)) -* Add maxWorkers to globalConfig ([#4005](https://github.com/facebook/jest/pull/4005)) -* Add skipped tests support for jest-editor-support ([#4346](https://github.com/facebook/jest/pull/4346)) -* Add source map support for better debugging experience ([#3738](https://github.com/facebook/jest/pull/3738)) -* Add support for Error objects in toMatchObject ([#4339](https://github.com/facebook/jest/pull/4339)) -* Add support for Immutable.Record in pretty-format ([#3678](https://github.com/facebook/jest/pull/3678)) -* Add tests for extract_requires on export types ([#4080](https://github.com/facebook/jest/pull/4080)) -* Add that toMatchObject can match arrays ([#3994](https://github.com/facebook/jest/pull/3994)) -* Add watchPathIgnorePatterns to exclude paths to trigger test re-run in watch mode ([#4331](https://github.com/facebook/jest/pull/4331)) -* Adding ancestorTitles property to JSON test output ([#4293](https://github.com/facebook/jest/pull/4293)) -* Allow custom resolver to be used with[out] moduleNameMapper ([#4174](https://github.com/facebook/jest/pull/4174)) -* Avoid parsing `.require(…)` method calls ([#3777](https://github.com/facebook/jest/pull/3777)) -* Avoid unnecessary function declarations and call in pretty-format ([#3962](https://github.com/facebook/jest/pull/3962)) -* Avoid writing to stdout in default reporter if --json is enabled. Fixes #3941 ([#3945](https://github.com/facebook/jest/pull/3945)) -* Better error handling for --config ([#4230](https://github.com/facebook/jest/pull/4230)) -* Call consistent pretty-format plugins within Jest ([#3800](https://github.com/facebook/jest/pull/3800)) -* Change babel-core to peerDependency for compatibility with Babel 7 ([#4162](https://github.com/facebook/jest/pull/4162)) -* Change Promise detection code in jest-circus to support non-global Promise implementations ([#4375](https://github.com/facebook/jest/pull/4375)) -* Changed files eager loading ([#3979](https://github.com/facebook/jest/pull/3979)) -* Check whether we should output to stdout or stderr ([#3953](https://github.com/facebook/jest/pull/3953)) -* Clarify what objects toContain and toContainEqual can be used on ([#4307](https://github.com/facebook/jest/pull/4307)) -* Clean up resolve() logic. Provide useful names for variables and functions. Test that a directory exists before attempting to resolve files within it. ([#4325](https://github.com/facebook/jest/pull/4325)) +* Add maxWorkers to globalConfig + ([#4005](https://github.com/facebook/jest/pull/4005)) +* Add skipped tests support for jest-editor-support + ([#4346](https://github.com/facebook/jest/pull/4346)) +* Add source map support for better debugging experience + ([#3738](https://github.com/facebook/jest/pull/3738)) +* Add support for Error objects in toMatchObject + ([#4339](https://github.com/facebook/jest/pull/4339)) +* Add support for Immutable.Record in pretty-format + ([#3678](https://github.com/facebook/jest/pull/3678)) +* Add tests for extract_requires on export types + ([#4080](https://github.com/facebook/jest/pull/4080)) +* Add that toMatchObject can match arrays + ([#3994](https://github.com/facebook/jest/pull/3994)) +* Add watchPathIgnorePatterns to exclude paths to trigger test re-run in watch + mode ([#4331](https://github.com/facebook/jest/pull/4331)) +* Adding ancestorTitles property to JSON test output + ([#4293](https://github.com/facebook/jest/pull/4293)) +* Allow custom resolver to be used with[out] moduleNameMapper + ([#4174](https://github.com/facebook/jest/pull/4174)) +* Avoid parsing `.require(…)` method calls + ([#3777](https://github.com/facebook/jest/pull/3777)) +* Avoid unnecessary function declarations and call in pretty-format + ([#3962](https://github.com/facebook/jest/pull/3962)) +* Avoid writing to stdout in default reporter if --json is enabled. Fixes #3941 + ([#3945](https://github.com/facebook/jest/pull/3945)) +* Better error handling for --config + ([#4230](https://github.com/facebook/jest/pull/4230)) +* Call consistent pretty-format plugins within Jest + ([#3800](https://github.com/facebook/jest/pull/3800)) +* Change babel-core to peerDependency for compatibility with Babel 7 + ([#4162](https://github.com/facebook/jest/pull/4162)) +* Change Promise detection code in jest-circus to support non-global Promise + implementations ([#4375](https://github.com/facebook/jest/pull/4375)) +* Changed files eager loading + ([#3979](https://github.com/facebook/jest/pull/3979)) +* Check whether we should output to stdout or stderr + ([#3953](https://github.com/facebook/jest/pull/3953)) +* Clarify what objects toContain and toContainEqual can be used on + ([#4307](https://github.com/facebook/jest/pull/4307)) +* Clean up resolve() logic. Provide useful names for variables and functions. + Test that a directory exists before attempting to resolve files within it. + ([#4325](https://github.com/facebook/jest/pull/4325)) * cleanupStackTrace ([#3696](https://github.com/facebook/jest/pull/3696)) -* compare objects with Symbol keys ([#3437](https://github.com/facebook/jest/pull/3437)) -* Complain if expect is passed multiple arguments ([#4237](https://github.com/facebook/jest/pull/4237)) -* Completes nodeCrawl with empty roots ([#3776](https://github.com/facebook/jest/pull/3776)) -* Consistent naming of files ([#3798](https://github.com/facebook/jest/pull/3798)) -* Convert code base to ESM import ([#3778](https://github.com/facebook/jest/pull/3778)) -* Correct summary message for flag --findRelatedTests. ([#4309](https://github.com/facebook/jest/pull/4309)) -* Coverage thresholds can be set up for individual files ([#4185](https://github.com/facebook/jest/pull/4185)) -* custom reporter error handling ([#4051](https://github.com/facebook/jest/pull/4051)) -* Define separate type for pretty-format plugin Options ([#3802](https://github.com/facebook/jest/pull/3802)) -* Delete confusing async keyword ([#3679](https://github.com/facebook/jest/pull/3679)) -* Delete redundant branch in ReactElement and HTMLElement plugins ([#3731](https://github.com/facebook/jest/pull/3731)) -* Don't format node assert errors when there's no 'assert' module ([#4376](https://github.com/facebook/jest/pull/4376)) -* Don't print test summary in --silent ([#4106](https://github.com/facebook/jest/pull/4106)) -* Don't try to build ghost packages ([#3934](https://github.com/facebook/jest/pull/3934)) -* Escape double quotes in attribute values in HTMLElement plugin ([#3797](https://github.com/facebook/jest/pull/3797)) -* Explain how to clear the cache ([#4232](https://github.com/facebook/jest/pull/4232)) -* Factor out common code for collections in pretty-format ([#4184](https://github.com/facebook/jest/pull/4184)) -* Factor out common code for markup in React plugins ([#4171](https://github.com/facebook/jest/pull/4171)) +* compare objects with Symbol keys + ([#3437](https://github.com/facebook/jest/pull/3437)) +* Complain if expect is passed multiple arguments + ([#4237](https://github.com/facebook/jest/pull/4237)) +* Completes nodeCrawl with empty roots + ([#3776](https://github.com/facebook/jest/pull/3776)) +* Consistent naming of files + ([#3798](https://github.com/facebook/jest/pull/3798)) +* Convert code base to ESM import + ([#3778](https://github.com/facebook/jest/pull/3778)) +* Correct summary message for flag --findRelatedTests. + ([#4309](https://github.com/facebook/jest/pull/4309)) +* Coverage thresholds can be set up for individual files + ([#4185](https://github.com/facebook/jest/pull/4185)) +* custom reporter error handling + ([#4051](https://github.com/facebook/jest/pull/4051)) +* Define separate type for pretty-format plugin Options + ([#3802](https://github.com/facebook/jest/pull/3802)) +* Delete confusing async keyword + ([#3679](https://github.com/facebook/jest/pull/3679)) +* Delete redundant branch in ReactElement and HTMLElement plugins + ([#3731](https://github.com/facebook/jest/pull/3731)) +* Don't format node assert errors when there's no 'assert' module + ([#4376](https://github.com/facebook/jest/pull/4376)) +* Don't print test summary in --silent + ([#4106](https://github.com/facebook/jest/pull/4106)) +* Don't try to build ghost packages + ([#3934](https://github.com/facebook/jest/pull/3934)) +* Escape double quotes in attribute values in HTMLElement plugin + ([#3797](https://github.com/facebook/jest/pull/3797)) +* Explain how to clear the cache + ([#4232](https://github.com/facebook/jest/pull/4232)) +* Factor out common code for collections in pretty-format + ([#4184](https://github.com/facebook/jest/pull/4184)) +* Factor out common code for markup in React plugins + ([#4171](https://github.com/facebook/jest/pull/4171)) * Feature/internal resolve ([#4315](https://github.com/facebook/jest/pull/4315)) * Fix --logHeapUsage ([#4176](https://github.com/facebook/jest/pull/4176)) -* Fix --showConfig to show all project configs ([#4078](https://github.com/facebook/jest/pull/4078)) +* Fix --showConfig to show all project configs + ([#4078](https://github.com/facebook/jest/pull/4078)) * Fix --watchAll ([#4254](https://github.com/facebook/jest/pull/4254)) -* Fix bug when setTimeout is mocked ([#3769](https://github.com/facebook/jest/pull/3769)) -* Fix changedFilesWithAncestor ([#4193](https://github.com/facebook/jest/pull/4193)) -* Fix colors for expected/stored snapshot message ([#3702](https://github.com/facebook/jest/pull/3702)) -* Fix concurrent test failure ([#4159](https://github.com/facebook/jest/pull/4159)) -* Fix for 4286: Compare Maps and Sets by value rather than order ([#4303](https://github.com/facebook/jest/pull/4303)) +* Fix bug when setTimeout is mocked + ([#3769](https://github.com/facebook/jest/pull/3769)) +* Fix changedFilesWithAncestor + ([#4193](https://github.com/facebook/jest/pull/4193)) +* Fix colors for expected/stored snapshot message + ([#3702](https://github.com/facebook/jest/pull/3702)) +* Fix concurrent test failure + ([#4159](https://github.com/facebook/jest/pull/4159)) +* Fix for 4286: Compare Maps and Sets by value rather than order + ([#4303](https://github.com/facebook/jest/pull/4303)) * fix forceExit ([#4105](https://github.com/facebook/jest/pull/4105)) -* Fix grammar in React Native docs ([#3838](https://github.com/facebook/jest/pull/3838)) -* Fix inconsistent name of complex values in pretty-format ([#4001](https://github.com/facebook/jest/pull/4001)) -* Fix issue mocking bound method ([#3805](https://github.com/facebook/jest/pull/3805)) +* Fix grammar in React Native docs + ([#3838](https://github.com/facebook/jest/pull/3838)) +* Fix inconsistent name of complex values in pretty-format + ([#4001](https://github.com/facebook/jest/pull/4001)) +* Fix issue mocking bound method + ([#3805](https://github.com/facebook/jest/pull/3805)) * Fix jest-circus ([#4290](https://github.com/facebook/jest/pull/4290)) -* Fix lint warning in master ([#4132](https://github.com/facebook/jest/pull/4132)) +* Fix lint warning in master + ([#4132](https://github.com/facebook/jest/pull/4132)) * Fix linting ([#3946](https://github.com/facebook/jest/pull/3946)) * fix merge conflict ([#4144](https://github.com/facebook/jest/pull/4144)) * Fix minor typo ([#3729](https://github.com/facebook/jest/pull/3729)) -* fix missing console.log messages ([#3895](https://github.com/facebook/jest/pull/3895)) +* fix missing console.log messages + ([#3895](https://github.com/facebook/jest/pull/3895)) * fix mock return value ([#3933](https://github.com/facebook/jest/pull/3933)) -* Fix mocking for modules with folders on windows ([#4238](https://github.com/facebook/jest/pull/4238)) -* Fix NODE_PATH resolving for relative paths ([#3616](https://github.com/facebook/jest/pull/3616)) -* Fix options.moduleNameMapper override order with preset ([#3565](https://github.com/facebook/jest/pull/3565) ([#3689](https://github.com/facebook/jest/pull/3689)) -* Fix React PropTypes warning in tests for Immutable plugin ([#4412](https://github.com/facebook/jest/pull/4412)) -* Fix regression in mockReturnValueOnce ([#3857](https://github.com/facebook/jest/pull/3857)) -* Fix sample code of mock class constructors ([#4115](https://github.com/facebook/jest/pull/4115)) -* Fix setup-test-framework-test ([#3773](https://github.com/facebook/jest/pull/3773)) -* fix typescript jest test crash ([#4363](https://github.com/facebook/jest/pull/4363)) +* Fix mocking for modules with folders on windows + ([#4238](https://github.com/facebook/jest/pull/4238)) +* Fix NODE_PATH resolving for relative paths + ([#3616](https://github.com/facebook/jest/pull/3616)) +* Fix options.moduleNameMapper override order with preset + ([#3565](https://github.com/facebook/jest/pull/3565) + ([#3689](https://github.com/facebook/jest/pull/3689)) +* Fix React PropTypes warning in tests for Immutable plugin + ([#4412](https://github.com/facebook/jest/pull/4412)) +* Fix regression in mockReturnValueOnce + ([#3857](https://github.com/facebook/jest/pull/3857)) +* Fix sample code of mock class constructors + ([#4115](https://github.com/facebook/jest/pull/4115)) +* Fix setup-test-framework-test + ([#3773](https://github.com/facebook/jest/pull/3773)) +* fix typescript jest test crash + ([#4363](https://github.com/facebook/jest/pull/4363)) * Fix watch mode ([#4084](https://github.com/facebook/jest/pull/4084)) * Fix Watchman on windows ([#4018](https://github.com/facebook/jest/pull/4018)) -* Fix(babel): Handle ignored files in babel v7 ([#4393](https://github.com/facebook/jest/pull/4393)) -* Fix(babel): Support upcoming beta ([#4403](https://github.com/facebook/jest/pull/4403)) +* Fix(babel): Handle ignored files in babel v7 + ([#4393](https://github.com/facebook/jest/pull/4393)) +* Fix(babel): Support upcoming beta + ([#4403](https://github.com/facebook/jest/pull/4403)) * Fixed object matcher ([#3799](https://github.com/facebook/jest/pull/3799)) * Fixes #3820 use extractExpectedAssertionsErrors in jasmine setup * Flow upgrade ([#4355](https://github.com/facebook/jest/pull/4355)) -* Force message in matchers to always be a function ([#3972](https://github.com/facebook/jest/pull/3972)) -* Format `describe` and use `test` instead of `it` alias ([#3792](https://github.com/facebook/jest/pull/3792)) -* global_config.js for multi-project runner ([#4023](https://github.com/facebook/jest/pull/4023)) +* Force message in matchers to always be a function + ([#3972](https://github.com/facebook/jest/pull/3972)) +* Format `describe` and use `test` instead of `it` alias + ([#3792](https://github.com/facebook/jest/pull/3792)) +* global_config.js for multi-project runner + ([#4023](https://github.com/facebook/jest/pull/4023)) * Handle async errors ([#4016](https://github.com/facebook/jest/pull/4016)) -* Hard-fail if hasteImpl is throwing an error during initialization. ([#3812](https://github.com/facebook/jest/pull/3812)) -* Ignore import type for extract_requires ([#4079](https://github.com/facebook/jest/pull/4079)) -* Ignore indentation of data structures in jest-diff ([#3429](https://github.com/facebook/jest/pull/3429)) -* Implement 'jest.requireMock' ([#4292](https://github.com/facebook/jest/pull/4292)) -* Improve Jest phabricator plugin ([#4195](https://github.com/facebook/jest/pull/4195)) -* Improve Seq and remove newline from non-min empty in Immutable plugin ([#4241](https://github.com/facebook/jest/pull/4241)) -* Improved the jest reporter with snapshot info per test. ([#3660](https://github.com/facebook/jest/pull/3660)) -* Include fullName in formattedAssertion ([#4273](https://github.com/facebook/jest/pull/4273)) -* Integrated with Yarn workspaces ([#3906](https://github.com/facebook/jest/pull/3906)) +* Hard-fail if hasteImpl is throwing an error during initialization. + ([#3812](https://github.com/facebook/jest/pull/3812)) +* Ignore import type for extract_requires + ([#4079](https://github.com/facebook/jest/pull/4079)) +* Ignore indentation of data structures in jest-diff + ([#3429](https://github.com/facebook/jest/pull/3429)) +* Implement 'jest.requireMock' + ([#4292](https://github.com/facebook/jest/pull/4292)) +* Improve Jest phabricator plugin + ([#4195](https://github.com/facebook/jest/pull/4195)) +* Improve Seq and remove newline from non-min empty in Immutable plugin + ([#4241](https://github.com/facebook/jest/pull/4241)) +* Improved the jest reporter with snapshot info per test. + ([#3660](https://github.com/facebook/jest/pull/3660)) +* Include fullName in formattedAssertion + ([#4273](https://github.com/facebook/jest/pull/4273)) +* Integrated with Yarn workspaces + ([#3906](https://github.com/facebook/jest/pull/3906)) * jest --all ([#4020](https://github.com/facebook/jest/pull/4020)) -* jest-circus test failures ([#3770](https://github.com/facebook/jest/pull/3770)) +* jest-circus test failures + ([#3770](https://github.com/facebook/jest/pull/3770)) * jest-circus Timeouts ([#3760](https://github.com/facebook/jest/pull/3760)) -* jest-haste-map: add test case for broken handling of ignore pattern ([#4047](https://github.com/facebook/jest/pull/4047)) -* jest-haste-map: add test+fix for broken platform module support ([#3885](https://github.com/facebook/jest/pull/3885)) -* jest-haste-map: deprecate functional ignorePattern and use it in cache key ([#4063](https://github.com/facebook/jest/pull/4063)) -* jest-haste-map: mock 'fs' with more idiomatic jest.mock() ([#4046](https://github.com/facebook/jest/pull/4046)) -* jest-haste-map: only file IO errors should be silently ignored ([#3816](https://github.com/facebook/jest/pull/3816)) -* jest-haste-map: throw when trying to get a duplicated module ([#3976](https://github.com/facebook/jest/pull/3976)) -* jest-haste-map: watchman crawler: normalize paths ([#3887](https://github.com/facebook/jest/pull/3887)) -* jest-runtime: atomic cache write, and check validity of data ([#4088](https://github.com/facebook/jest/pull/4088)) -* Join lines with newline in jest-diff ([#4314](https://github.com/facebook/jest/pull/4314)) -* Keep ARGV only in CLI files ([#4012](https://github.com/facebook/jest/pull/4012)) -* let transformers adjust cache key based on mapCoverage ([#4187](https://github.com/facebook/jest/pull/4187)) +* jest-haste-map: add test case for broken handling of ignore pattern + ([#4047](https://github.com/facebook/jest/pull/4047)) +* jest-haste-map: add test+fix for broken platform module support + ([#3885](https://github.com/facebook/jest/pull/3885)) +* jest-haste-map: deprecate functional ignorePattern and use it in cache key + ([#4063](https://github.com/facebook/jest/pull/4063)) +* jest-haste-map: mock 'fs' with more idiomatic jest.mock() + ([#4046](https://github.com/facebook/jest/pull/4046)) +* jest-haste-map: only file IO errors should be silently ignored + ([#3816](https://github.com/facebook/jest/pull/3816)) +* jest-haste-map: throw when trying to get a duplicated module + ([#3976](https://github.com/facebook/jest/pull/3976)) +* jest-haste-map: watchman crawler: normalize paths + ([#3887](https://github.com/facebook/jest/pull/3887)) +* jest-runtime: atomic cache write, and check validity of data + ([#4088](https://github.com/facebook/jest/pull/4088)) +* Join lines with newline in jest-diff + ([#4314](https://github.com/facebook/jest/pull/4314)) +* Keep ARGV only in CLI files + ([#4012](https://github.com/facebook/jest/pull/4012)) +* let transformers adjust cache key based on mapCoverage + ([#4187](https://github.com/facebook/jest/pull/4187)) * Lift requires ([#3780](https://github.com/facebook/jest/pull/3780)) -* Log stack when reporting errors in jest-runtime ([#3833](https://github.com/facebook/jest/pull/3833)) -* Make --listTests return a new line separated list when not using --json ([#4229](https://github.com/facebook/jest/pull/4229)) -* Make build script printing small-terminals-friendly ([#3892](https://github.com/facebook/jest/pull/3892)) -* Make error messages more explicit for toBeCalledWith assertions ([#3913](https://github.com/facebook/jest/pull/3913)) -* Make jest-matcher-utils use ESM exports ([#4342](https://github.com/facebook/jest/pull/4342)) -* Make jest-runner a standalone package. ([#4236](https://github.com/facebook/jest/pull/4236)) -* Make Jest’s Test Runner configurable. ([#4240](https://github.com/facebook/jest/pull/4240)) -* Make listTests always print to console.log ([#4391](https://github.com/facebook/jest/pull/4391)) +* Log stack when reporting errors in jest-runtime + ([#3833](https://github.com/facebook/jest/pull/3833)) +* Make --listTests return a new line separated list when not using --json + ([#4229](https://github.com/facebook/jest/pull/4229)) +* Make build script printing small-terminals-friendly + ([#3892](https://github.com/facebook/jest/pull/3892)) +* Make error messages more explicit for toBeCalledWith assertions + ([#3913](https://github.com/facebook/jest/pull/3913)) +* Make jest-matcher-utils use ESM exports + ([#4342](https://github.com/facebook/jest/pull/4342)) +* Make jest-runner a standalone package. + ([#4236](https://github.com/facebook/jest/pull/4236)) +* Make Jest’s Test Runner configurable. + ([#4240](https://github.com/facebook/jest/pull/4240)) +* Make listTests always print to console.log + ([#4391](https://github.com/facebook/jest/pull/4391)) * Make providesModuleNodeModules ignore nested node_modules directories -* Make sure function mocks match original arity ([#4170](https://github.com/facebook/jest/pull/4170)) -* Make sure runAllTimers also clears all ticks ([#3915](https://github.com/facebook/jest/pull/3915)) -* Make toBe matcher error message more helpful for objects and arrays ([#4277](https://github.com/facebook/jest/pull/4277)) -* Make useRealTimers play well with timers: fake ([#3858](https://github.com/facebook/jest/pull/3858)) -* Move getType from jest-matcher-utils to separate package ([#3559](https://github.com/facebook/jest/pull/3559)) -* Multiroot jest-change-files ([#3969](https://github.com/facebook/jest/pull/3969)) -* Output created snapshot when using --ci option ([#3693](https://github.com/facebook/jest/pull/3693)) -* Point out you can use matchers in .toMatchObject ([#3796](https://github.com/facebook/jest/pull/3796)) -* Prevent babelrc package import failure on relative current path ([#3723](https://github.com/facebook/jest/pull/3723)) -* Print RDP details for windows builds ([#4017](https://github.com/facebook/jest/pull/4017)) -* Provide better error checking for transformed content ([#3807](https://github.com/facebook/jest/pull/3807)) -* Provide printText and printComment in markup.js for HTMLElement plugin ([#4344](https://github.com/facebook/jest/pull/4344)) -* Provide regex visualization for testRegex ([#3758](https://github.com/facebook/jest/pull/3758)) +* Make sure function mocks match original arity + ([#4170](https://github.com/facebook/jest/pull/4170)) +* Make sure runAllTimers also clears all ticks + ([#3915](https://github.com/facebook/jest/pull/3915)) +* Make toBe matcher error message more helpful for objects and arrays + ([#4277](https://github.com/facebook/jest/pull/4277)) +* Make useRealTimers play well with timers: fake + ([#3858](https://github.com/facebook/jest/pull/3858)) +* Move getType from jest-matcher-utils to separate package + ([#3559](https://github.com/facebook/jest/pull/3559)) +* Multiroot jest-change-files + ([#3969](https://github.com/facebook/jest/pull/3969)) +* Output created snapshot when using --ci option + ([#3693](https://github.com/facebook/jest/pull/3693)) +* Point out you can use matchers in .toMatchObject + ([#3796](https://github.com/facebook/jest/pull/3796)) +* Prevent babelrc package import failure on relative current path + ([#3723](https://github.com/facebook/jest/pull/3723)) +* Print RDP details for windows builds + ([#4017](https://github.com/facebook/jest/pull/4017)) +* Provide better error checking for transformed content + ([#3807](https://github.com/facebook/jest/pull/3807)) +* Provide printText and printComment in markup.js for HTMLElement plugin + ([#4344](https://github.com/facebook/jest/pull/4344)) +* Provide regex visualization for testRegex + ([#3758](https://github.com/facebook/jest/pull/3758)) * Refactor CLI ([#3862](https://github.com/facebook/jest/pull/3862)) -* Refactor names and delimiters of complex values in pretty-format ([#3986](https://github.com/facebook/jest/pull/3986)) -* Replace concat(Immutable) with Immutable as item of plugins array ([#4207](https://github.com/facebook/jest/pull/4207)) -* Replace Jasmine with jest-circus ([#3668](https://github.com/facebook/jest/pull/3668)) -* Replace match with test and omit redundant String conversion ([#4311](https://github.com/facebook/jest/pull/4311)) -* Replace print with serialize in AsymmetricMatcher plugin ([#4173](https://github.com/facebook/jest/pull/4173)) -* Replace print with serialize in ConvertAnsi plugin ([#4225](https://github.com/facebook/jest/pull/4225)) -* Replace print with serialize in HTMLElement plugin ([#4215](https://github.com/facebook/jest/pull/4215)) -* Replace print with serialize in Immutable plugins ([#4189](https://github.com/facebook/jest/pull/4189)) -* Replace unchanging args with one config arg within pretty-format ([#4076](https://github.com/facebook/jest/pull/4076)) -* Return UNDEFINED for undefined type in ReactElement plugin ([#4360](https://github.com/facebook/jest/pull/4360)) -* Rewrite some read bumps in pretty-format ([#4093](https://github.com/facebook/jest/pull/4093)) -* Run update method before installing JRE on Circle ([#4318](https://github.com/facebook/jest/pull/4318)) -* Separated the snapshot summary creation from the printing to improve testability. ([#4373](https://github.com/facebook/jest/pull/4373)) -* Set coverageDirectory during normalize phase ([#3966](https://github.com/facebook/jest/pull/3966)) -* Setup custom reporters after default reporters ([#4053](https://github.com/facebook/jest/pull/4053)) +* Refactor names and delimiters of complex values in pretty-format + ([#3986](https://github.com/facebook/jest/pull/3986)) +* Replace concat(Immutable) with Immutable as item of plugins array + ([#4207](https://github.com/facebook/jest/pull/4207)) +* Replace Jasmine with jest-circus + ([#3668](https://github.com/facebook/jest/pull/3668)) +* Replace match with test and omit redundant String conversion + ([#4311](https://github.com/facebook/jest/pull/4311)) +* Replace print with serialize in AsymmetricMatcher plugin + ([#4173](https://github.com/facebook/jest/pull/4173)) +* Replace print with serialize in ConvertAnsi plugin + ([#4225](https://github.com/facebook/jest/pull/4225)) +* Replace print with serialize in HTMLElement plugin + ([#4215](https://github.com/facebook/jest/pull/4215)) +* Replace print with serialize in Immutable plugins + ([#4189](https://github.com/facebook/jest/pull/4189)) +* Replace unchanging args with one config arg within pretty-format + ([#4076](https://github.com/facebook/jest/pull/4076)) +* Return UNDEFINED for undefined type in ReactElement plugin + ([#4360](https://github.com/facebook/jest/pull/4360)) +* Rewrite some read bumps in pretty-format + ([#4093](https://github.com/facebook/jest/pull/4093)) +* Run update method before installing JRE on Circle + ([#4318](https://github.com/facebook/jest/pull/4318)) +* Separated the snapshot summary creation from the printing to improve + testability. ([#4373](https://github.com/facebook/jest/pull/4373)) +* Set coverageDirectory during normalize phase + ([#3966](https://github.com/facebook/jest/pull/3966)) +* Setup custom reporters after default reporters + ([#4053](https://github.com/facebook/jest/pull/4053)) * Setup for Circle 2 ([#4149](https://github.com/facebook/jest/pull/4149)) * Simplify readme ([#3790](https://github.com/facebook/jest/pull/3790)) -* Simplify snapshots definition ([#3791](https://github.com/facebook/jest/pull/3791)) -* skipNodeResolution config option ([#3987](https://github.com/facebook/jest/pull/3987)) -* Small fixes to toHaveProperty docs ([#3878](https://github.com/facebook/jest/pull/3878)) -* Sort attributes by name in HTMLElement plugin ([#3783](https://github.com/facebook/jest/pull/3783)) -* Specify watchPathIgnorePatterns will only be available in Jest 21+ ([#4398](https://github.com/facebook/jest/pull/4398)) -* Split TestRunner off of TestScheduler ([#4233](https://github.com/facebook/jest/pull/4233)) -* Strict and explicit config resolution logic ([#4122](https://github.com/facebook/jest/pull/4122)) -* Support maxDepth option in React plugins ([#4208](https://github.com/facebook/jest/pull/4208)) -* Support SVG elements in HTMLElement plugin ([#4335](https://github.com/facebook/jest/pull/4335)) -* Test empty Immutable collections with {min: false} option ([#4121](https://github.com/facebook/jest/pull/4121)) -* test to debug travis failure in master ([#4145](https://github.com/facebook/jest/pull/4145)) -* testPathPattern message test ([#4006](https://github.com/facebook/jest/pull/4006)) -* Throw Error When Using Nested It Specs ([#4039](https://github.com/facebook/jest/pull/4039)) -* Throw when moduleNameMapper points to inexistent module ([#3567](https://github.com/facebook/jest/pull/3567)) -* Unified 'no tests found' message for non-verbose MPR ([#4354](https://github.com/facebook/jest/pull/4354)) -* Update migration guide with jest-codemods transformers ([#4306](https://github.com/facebook/jest/pull/4306)) -* Use "inputSourceMap" for coverage re-mapping. ([#4009](https://github.com/facebook/jest/pull/4009)) -* Use "verbose" no test found message when there is only one project ([#4378](https://github.com/facebook/jest/pull/4378)) -* Use babel transform to inline all requires ([#4340](https://github.com/facebook/jest/pull/4340)) -* Use eslint plugins to run prettier ([#3971](https://github.com/facebook/jest/pull/3971)) -* Use iterableEquality in spy matchers ([#3651](https://github.com/facebook/jest/pull/3651)) -* Use modern HTML5 ([#3937](https://github.com/facebook/jest/pull/3937)) -* Wrap `Error.captureStackTrace` in a try ([#4035](https://github.com/facebook/jest/pull/4035)) +* Simplify snapshots definition + ([#3791](https://github.com/facebook/jest/pull/3791)) +* skipNodeResolution config option + ([#3987](https://github.com/facebook/jest/pull/3987)) +* Small fixes to toHaveProperty docs + ([#3878](https://github.com/facebook/jest/pull/3878)) +* Sort attributes by name in HTMLElement plugin + ([#3783](https://github.com/facebook/jest/pull/3783)) +* Specify watchPathIgnorePatterns will only be available in Jest 21+ + ([#4398](https://github.com/facebook/jest/pull/4398)) +* Split TestRunner off of TestScheduler + ([#4233](https://github.com/facebook/jest/pull/4233)) +* Strict and explicit config resolution logic + ([#4122](https://github.com/facebook/jest/pull/4122)) +* Support maxDepth option in React plugins + ([#4208](https://github.com/facebook/jest/pull/4208)) +* Support SVG elements in HTMLElement plugin + ([#4335](https://github.com/facebook/jest/pull/4335)) +* Test empty Immutable collections with {min: false} option + ([#4121](https://github.com/facebook/jest/pull/4121)) +* test to debug travis failure in master + ([#4145](https://github.com/facebook/jest/pull/4145)) +* testPathPattern message test + ([#4006](https://github.com/facebook/jest/pull/4006)) +* Throw Error When Using Nested It Specs + ([#4039](https://github.com/facebook/jest/pull/4039)) +* Throw when moduleNameMapper points to inexistent module + ([#3567](https://github.com/facebook/jest/pull/3567)) +* Unified 'no tests found' message for non-verbose MPR + ([#4354](https://github.com/facebook/jest/pull/4354)) +* Update migration guide with jest-codemods transformers + ([#4306](https://github.com/facebook/jest/pull/4306)) +* Use "inputSourceMap" for coverage re-mapping. + ([#4009](https://github.com/facebook/jest/pull/4009)) +* Use "verbose" no test found message when there is only one project + ([#4378](https://github.com/facebook/jest/pull/4378)) +* Use babel transform to inline all requires + ([#4340](https://github.com/facebook/jest/pull/4340)) +* Use eslint plugins to run prettier + ([#3971](https://github.com/facebook/jest/pull/3971)) +* Use iterableEquality in spy matchers + ([#3651](https://github.com/facebook/jest/pull/3651)) +* Use modern HTML5 + ([#3937](https://github.com/facebook/jest/pull/3937)) +* Wrap `Error.captureStackTrace` in a try + ([#4035](https://github.com/facebook/jest/pull/4035)) ## jest 20.0.4 -* Fix jest-haste-map's handling of duplicate module IDs. ([#3647](https://github.com/facebook/jest/pull/3647)) -* Fix behavior of `enableAutomock()` when automock is set to false. ([#3624](https://github.com/facebook/jest/pull/3624)) -* Fix progress bar in windows. ([#3626](https://github.com/facebook/jest/pull/3626)) +* Fix jest-haste-map's handling of duplicate module IDs. + ([#3647](https://github.com/facebook/jest/pull/3647)) +* Fix behavior of `enableAutomock()` when automock is set to false. + ([#3624](https://github.com/facebook/jest/pull/3624)) +* Fix progress bar in windows. + ([#3626](https://github.com/facebook/jest/pull/3626)) ## jest 20.0.3 -* Fix reporters 'default' setting. ([#3562](https://github.com/facebook/jest/pull/3562)) -* Fix to make Jest fail when the coverage threshold not met. ([#3554](https://github.com/facebook/jest/pull/3554)) +* Fix reporters 'default' setting. + ([#3562](https://github.com/facebook/jest/pull/3562)) +* Fix to make Jest fail when the coverage threshold not met. + ([#3554](https://github.com/facebook/jest/pull/3554)) ## jest 20.0.1 -* Add ansi-regex to pretty-format dependencies ([#3498](https://github.com/facebook/jest/pull/3498)) -* Fix replacement in testMatch and moduleDirectories ([#3538](https://github.com/facebook/jest/pull/3538)) -* Fix expect.hasAssertions() to throw when passed arguments ([#3526](https://github.com/facebook/jest/pull/3526)) -* Fix stack traces without proper error messages ([#3513](https://github.com/facebook/jest/pull/3513)) -* Fix support for custom extensions through haste packages ([#3537](https://github.com/facebook/jest/pull/3537)) -* Fix test contexts between test functions ([#3506](https://github.com/facebook/jest/pull/3506)) +* Add ansi-regex to pretty-format dependencies + ([#3498](https://github.com/facebook/jest/pull/3498)) +* Fix replacement in testMatch and moduleDirectories + ([#3538](https://github.com/facebook/jest/pull/3538)) +* Fix expect.hasAssertions() to throw when passed arguments + ([#3526](https://github.com/facebook/jest/pull/3526)) +* Fix stack traces without proper error messages + ([#3513](https://github.com/facebook/jest/pull/3513)) +* Fix support for custom extensions through haste packages + ([#3537](https://github.com/facebook/jest/pull/3537)) +* Fix test contexts between test functions + ([#3506](https://github.com/facebook/jest/pull/3506)) ## jest 20.0.0 -* New `--projects` option to run one instance of Jest in multiple projects at the same time. ([#3400](https://github.com/facebook/jest/pull/3400)) +* New `--projects` option to run one instance of Jest in multiple projects at + the same time. ([#3400](https://github.com/facebook/jest/pull/3400)) * New multi project runner ([#3156](https://github.com/facebook/jest/pull/3156)) * New --listTests flag. ([#3441](https://github.com/facebook/jest/pull/3441)) * New --showConfig flag. ([#3296](https://github.com/facebook/jest/pull/3296)) -* New promise support for all `expect` matchers through `.resolves` and `.rejects`. ([#3068](https://github.com/facebook/jest/pull/3068)) -* New `expect.hasAssertions()` function similar to `expect.assertions()`. ([#3379](https://github.com/facebook/jest/pull/3379)) -* New `this.equals` function exposed to custom matchers. ([#3469](https://github.com/facebook/jest/pull/3469)) -* New `valid-expect` lint rule in `eslint-plugin-jest`. ([#3067](https://github.com/facebook/jest/pull/3067)) -* New HtmlElement pretty-format plugin. ([#3230](https://github.com/facebook/jest/pull/3230)) -* New Immutable pretty-format plugins. ([#2899](https://github.com/facebook/jest/pull/2899)) -* New test environment per file setting through `@jest-environment` in the docblock. ([#2859](https://github.com/facebook/jest/pull/2859)) -* New feature that allows every configuration option to be set from the command line. ([#3424](https://github.com/facebook/jest/pull/3424)) -* New feature to add custom reporters to Jest through `reporters` in the configuration. ([#3349](https://github.com/facebook/jest/pull/3349)) -* New feature to add expected and actual values to AssertionError. ([#3217](https://github.com/facebook/jest/pull/3217)) -* New feature to map code coverage from transformers. ([#2290](https://github.com/facebook/jest/pull/2290)) -* New feature to run untested code coverage in parallel. ([#3407](https://github.com/facebook/jest/pull/3407)) -* New option to define a custom resolver. ([#2998](https://github.com/facebook/jest/pull/2998)) -* New printing support for text and comment nodes in html pretty-format. ([#3355](https://github.com/facebook/jest/pull/3355)) +* New promise support for all `expect` matchers through `.resolves` and + `.rejects`. ([#3068](https://github.com/facebook/jest/pull/3068)) +* New `expect.hasAssertions()` function similar to `expect.assertions()`. + ([#3379](https://github.com/facebook/jest/pull/3379)) +* New `this.equals` function exposed to custom matchers. + ([#3469](https://github.com/facebook/jest/pull/3469)) +* New `valid-expect` lint rule in `eslint-plugin-jest`. + ([#3067](https://github.com/facebook/jest/pull/3067)) +* New HtmlElement pretty-format plugin. + ([#3230](https://github.com/facebook/jest/pull/3230)) +* New Immutable pretty-format plugins. + ([#2899](https://github.com/facebook/jest/pull/2899)) +* New test environment per file setting through `@jest-environment` in the + docblock. ([#2859](https://github.com/facebook/jest/pull/2859)) +* New feature that allows every configuration option to be set from the command + line. ([#3424](https://github.com/facebook/jest/pull/3424)) +* New feature to add custom reporters to Jest through `reporters` in the + configuration. ([#3349](https://github.com/facebook/jest/pull/3349)) +* New feature to add expected and actual values to AssertionError. + ([#3217](https://github.com/facebook/jest/pull/3217)) +* New feature to map code coverage from transformers. + ([#2290](https://github.com/facebook/jest/pull/2290)) +* New feature to run untested code coverage in parallel. + ([#3407](https://github.com/facebook/jest/pull/3407)) +* New option to define a custom resolver. + ([#2998](https://github.com/facebook/jest/pull/2998)) +* New printing support for text and comment nodes in html pretty-format. + ([#3355](https://github.com/facebook/jest/pull/3355)) * New snapshot testing FAQ ([#3425](https://github.com/facebook/jest/pull/3425)) -* New support for custom platforms on jest-haste-map. ([#3162](https://github.com/facebook/jest/pull/3162)) -* New support for mocking native async methods. ([#3209](https://github.com/facebook/jest/pull/3209)) -* New guide on how to use Jest with any JavaScript framework. ([#3243](https://github.com/facebook/jest/pull/3243)) +* New support for custom platforms on jest-haste-map. + ([#3162](https://github.com/facebook/jest/pull/3162)) +* New support for mocking native async methods. + ([#3209](https://github.com/facebook/jest/pull/3209)) +* New guide on how to use Jest with any JavaScript framework. + ([#3243](https://github.com/facebook/jest/pull/3243)) * New translation system for the Jest website. -* New collapsing watch mode usage prompt after first run. ([#3078](https://github.com/facebook/jest/pull/3078)) -* Breaking Change: Forked Jasmine 2.5 into Jest's own test runner and rewrote large parts of Jasmine. ([#3147](https://github.com/facebook/jest/pull/3147)) -* Breaking Change: Jest does not write new snapshots by default on CI. ([#3456](https://github.com/facebook/jest/pull/3456)) -* Breaking Change: Moved the typescript parser from `jest-editor-support` into a separate `jest-test-typescript-parser` package. ([#2973](https://github.com/facebook/jest/pull/2973)) -* Breaking Change: Replaced auto-loading of babel-polyfill with only regenerator-runtime, fixes a major memory leak. ([#2755](https://github.com/facebook/jest/pull/2755)) -* Fixed `babel-jest` to look up the `babel` field in `package.json` as a fallback. -* Fixed `jest-editor-support`'s parser to not crash on incomplete ASTs. ([#3259](https://github.com/facebook/jest/pull/3259)) -* Fixed `jest-resolve` to use `is-builtin-module` instead of `resolve.isCore`. ([#2997](https://github.com/facebook/jest/pull/2997)) -* Fixed `jest-snapshot` to normalize line endings in the `serialize` function. ([#3002](https://github.com/facebook/jest/pull/3002)) -* Fixed behavior of `--silent` flag. ([#3003](https://github.com/facebook/jest/pull/3003)) -* Fixed bug with watchers on macOS causing test to crash. ([#2957](https://github.com/facebook/jest/pull/2957)) -* Fixed CLI `notify` option not taking precedence over config option. ([#3340](https://github.com/facebook/jest/pull/3340)) -* Fixed detection of the npm client in SummaryReporter to support Yarn. ([#3263](https://github.com/facebook/jest/pull/3263)) -* Fixed done.fail not passing arguments ([#3241](https://github.com/facebook/jest/pull/3241)) -* Fixed fake timers to restore after resetting mocks. ([#2467](https://github.com/facebook/jest/pull/2467)) -* Fixed handling of babylon's parser options in `jest-editor-support`. ([#3344](https://github.com/facebook/jest/pull/3344)) -* Fixed Jest to properly cache transform results. ([#3334](https://github.com/facebook/jest/pull/3334)) -* Fixed Jest to use human-readable colors for Jest's own snapshots. ([#3119](https://github.com/facebook/jest/pull/3119)) -* Fixed jest-config to use UID for default cache folder. ([#3380](https://github.com/facebook/jest/pull/3380)), ([#3387](https://github.com/facebook/jest/pull/3387)) -* Fixed jest-runtime to expose inner error when it fails to write to the cache. ([#3373](https://github.com/facebook/jest/pull/3373)) -* Fixed lifecycle hooks to make afterAll hooks operate the same as afterEach. ([#3275](https://github.com/facebook/jest/pull/3275)) -* Fixed pretty-format to run plugins before serializing nested basic values. ([#3017](https://github.com/facebook/jest/pull/3017)) -* Fixed return value of mocks so they can explicitly be set to return `undefined`. ([#3354](https://github.com/facebook/jest/pull/3354)) -* Fixed runner to run tests associated with snapshots when the snapshot changes. ([#3025](https://github.com/facebook/jest/pull/3025)) -* Fixed snapshot serializer require, restructured pretty-format. ([#3399](https://github.com/facebook/jest/pull/3399)) -* Fixed support for Babel 7 in babel-jest. ([#3271](https://github.com/facebook/jest/pull/3271)) -* Fixed testMatch to find tests in .folders. ([#3006](https://github.com/facebook/jest/pull/3006)) -* Fixed testNamePattern and testPathPattern to work better together. ([#3327](https://github.com/facebook/jest/pull/3327)) -* Fixed to show reject reason when expecting resolve. ([#3134](https://github.com/facebook/jest/pull/3134)) -* Fixed toHaveProperty() to use hasOwnProperty from Object ([#3410](https://github.com/facebook/jest/pull/3410)) -* Fixed watch mode's screen clearing. ([#2959](https://github.com/facebook/jest/pull/2959)) ([#3294](https://github.com/facebook/jest/pull/3294)) -* Improved and consolidated Jest's configuration file resolution. ([#3472](https://github.com/facebook/jest/pull/3472)) +* New collapsing watch mode usage prompt after first run. + ([#3078](https://github.com/facebook/jest/pull/3078)) +* Breaking Change: Forked Jasmine 2.5 into Jest's own test runner and rewrote + large parts of Jasmine. ([#3147](https://github.com/facebook/jest/pull/3147)) +* Breaking Change: Jest does not write new snapshots by default on CI. + ([#3456](https://github.com/facebook/jest/pull/3456)) +* Breaking Change: Moved the typescript parser from `jest-editor-support` into a + separate `jest-test-typescript-parser` package. + ([#2973](https://github.com/facebook/jest/pull/2973)) +* Breaking Change: Replaced auto-loading of babel-polyfill with only + regenerator-runtime, fixes a major memory leak. + ([#2755](https://github.com/facebook/jest/pull/2755)) +* Fixed `babel-jest` to look up the `babel` field in `package.json` as a + fallback. +* Fixed `jest-editor-support`'s parser to not crash on incomplete ASTs. + ([#3259](https://github.com/facebook/jest/pull/3259)) +* Fixed `jest-resolve` to use `is-builtin-module` instead of `resolve.isCore`. + ([#2997](https://github.com/facebook/jest/pull/2997)) +* Fixed `jest-snapshot` to normalize line endings in the `serialize` function. + ([#3002](https://github.com/facebook/jest/pull/3002)) +* Fixed behavior of `--silent` flag. + ([#3003](https://github.com/facebook/jest/pull/3003)) +* Fixed bug with watchers on macOS causing test to crash. + ([#2957](https://github.com/facebook/jest/pull/2957)) +* Fixed CLI `notify` option not taking precedence over config option. + ([#3340](https://github.com/facebook/jest/pull/3340)) +* Fixed detection of the npm client in SummaryReporter to support Yarn. + ([#3263](https://github.com/facebook/jest/pull/3263)) +* Fixed done.fail not passing arguments + ([#3241](https://github.com/facebook/jest/pull/3241)) +* Fixed fake timers to restore after resetting mocks. + ([#2467](https://github.com/facebook/jest/pull/2467)) +* Fixed handling of babylon's parser options in `jest-editor-support`. + ([#3344](https://github.com/facebook/jest/pull/3344)) +* Fixed Jest to properly cache transform results. + ([#3334](https://github.com/facebook/jest/pull/3334)) +* Fixed Jest to use human-readable colors for Jest's own snapshots. + ([#3119](https://github.com/facebook/jest/pull/3119)) +* Fixed jest-config to use UID for default cache folder. + ([#3380](https://github.com/facebook/jest/pull/3380)), + ([#3387](https://github.com/facebook/jest/pull/3387)) +* Fixed jest-runtime to expose inner error when it fails to write to the cache. + ([#3373](https://github.com/facebook/jest/pull/3373)) +* Fixed lifecycle hooks to make afterAll hooks operate the same as afterEach. + ([#3275](https://github.com/facebook/jest/pull/3275)) +* Fixed pretty-format to run plugins before serializing nested basic values. + ([#3017](https://github.com/facebook/jest/pull/3017)) +* Fixed return value of mocks so they can explicitly be set to return + `undefined`. ([#3354](https://github.com/facebook/jest/pull/3354)) +* Fixed runner to run tests associated with snapshots when the snapshot changes. + ([#3025](https://github.com/facebook/jest/pull/3025)) +* Fixed snapshot serializer require, restructured pretty-format. + ([#3399](https://github.com/facebook/jest/pull/3399)) +* Fixed support for Babel 7 in babel-jest. + ([#3271](https://github.com/facebook/jest/pull/3271)) +* Fixed testMatch to find tests in .folders. + ([#3006](https://github.com/facebook/jest/pull/3006)) +* Fixed testNamePattern and testPathPattern to work better together. + ([#3327](https://github.com/facebook/jest/pull/3327)) +* Fixed to show reject reason when expecting resolve. + ([#3134](https://github.com/facebook/jest/pull/3134)) +* Fixed toHaveProperty() to use hasOwnProperty from Object + ([#3410](https://github.com/facebook/jest/pull/3410)) +* Fixed watch mode's screen clearing. + ([#2959](https://github.com/facebook/jest/pull/2959)) + ([#3294](https://github.com/facebook/jest/pull/3294)) +* Improved and consolidated Jest's configuration file resolution. + ([#3472](https://github.com/facebook/jest/pull/3472)) * Improved documentation throughout the Jest website. -* Improved documentation to explicitly mention that snapshots must be reviewed. ([#3203](https://github.com/facebook/jest/pull/3203)) -* Improved documentation to make it clear CRA users don't need to add dependencies. ([#3312](https://github.com/facebook/jest/pull/3312)) -* Improved eslint-plugin-jest's handling of `expect`. ([#3306](https://github.com/facebook/jest/pull/3306)) -* Improved flow-coverage, eslint rules and test coverage within the Jest repository. -* Improved printing of `expect.assertions` error. ([#3033](https://github.com/facebook/jest/pull/3033)) +* Improved documentation to explicitly mention that snapshots must be reviewed. + ([#3203](https://github.com/facebook/jest/pull/3203)) +* Improved documentation to make it clear CRA users don't need to add + dependencies. ([#3312](https://github.com/facebook/jest/pull/3312)) +* Improved eslint-plugin-jest's handling of `expect`. + ([#3306](https://github.com/facebook/jest/pull/3306)) +* Improved flow-coverage, eslint rules and test coverage within the Jest + repository. +* Improved printing of `expect.assertions` error. + ([#3033](https://github.com/facebook/jest/pull/3033)) * Improved Windows test coverage of Jest. -* Refactored configs & transform ([#3376](https://github.com/facebook/jest/pull/3376)) -* Refactored reporters to pass individual Tests to reporters. ([#3289](https://github.com/facebook/jest/pull/3289)) +* Refactored configs & transform + ([#3376](https://github.com/facebook/jest/pull/3376)) +* Refactored reporters to pass individual Tests to reporters. + ([#3289](https://github.com/facebook/jest/pull/3289)) * Refactored TestRunner ([#3166](https://github.com/facebook/jest/pull/3166)) -* Refactored watch mode prompts. ([#3290](https://github.com/facebook/jest/pull/3290)) -* Deleted `jest-file-exists`. ([#3105](https://github.com/facebook/jest/pull/3105)) +* Refactored watch mode prompts. + ([#3290](https://github.com/facebook/jest/pull/3290)) +* Deleted `jest-file-exists`. + ([#3105](https://github.com/facebook/jest/pull/3105)) * Removed `Config` type. ([#3366](https://github.com/facebook/jest/pull/3366)) -* Removed all usage of `jest-file-exists`. ([#3101](https://github.com/facebook/jest/pull/3101)) +* Removed all usage of `jest-file-exists`. + ([#3101](https://github.com/facebook/jest/pull/3101)) * Adopted prettier on the Jest codebase. ## jest 19.0.1 @@ -387,54 +700,71 @@ ## jest 19.0.0 * Breaking Change: Added a version for snapshots. -* Breaking Change: Removed the `mocksPattern` configuration option, it never worked correctly. -* Breaking Change: Renamed `testPathDirs` to `roots` to avoid confusion when configuring Jest. -* Breaking Change: Updated printing of React elements to cause fewer changes when props change. +* Breaking Change: Removed the `mocksPattern` configuration option, it never + worked correctly. +* Breaking Change: Renamed `testPathDirs` to `roots` to avoid confusion when + configuring Jest. +* Breaking Change: Updated printing of React elements to cause fewer changes + when props change. * Breaking Change: Updated snapshot format to properly escape data. * Fixed --color to be recognized correctly again. -* Fixed `babel-plugin-jest-hoist` to work properly with type annotations in tests. +* Fixed `babel-plugin-jest-hoist` to work properly with type annotations in + tests. * Fixed behavior for console.log calls and fixed a memory leak (#2539). * Fixed cache directory path for Jest to avoid ENAMETOOLONG errors. -* Fixed change events to be emitted in jest-haste-map's watch mode. This fixes issues with Jest's new watch mode and react-native-packager. -* Fixed cli arguments to be used when loading the config from file, they were previously ignored. +* Fixed change events to be emitted in jest-haste-map's watch mode. This fixes + issues with Jest's new watch mode and react-native-packager. +* Fixed cli arguments to be used when loading the config from file, they were + previously ignored. * Fixed Jest to load json files that include a BOM. * Fixed Jest to throw errors instead of ignoring invalid cli options. * Fixed mocking behavior for virtual modules. * Fixed mocking behavior with transitive dependencies. * Fixed support for asymmetric matchers in `toMatchObject`. * Fixed test interruption and `--bail` behavior. -* Fixed watch mode to clean up worker processes when a test run gets interrupted. +* Fixed watch mode to clean up worker processes when a test run gets + interrupted. * Fixed whitespace to be highlighted in snapshots and assertion errors. -* Improved `babel-jest` plugin: babel is loaded lazily, istanbul comments are only added when coverage is used. +* Improved `babel-jest` plugin: babel is loaded lazily, istanbul comments are + only added when coverage is used. * Improved error for invalid transform config. -* Improved moduleNameMapper to not overwrite mocks when many patterns map to the same file. +* Improved moduleNameMapper to not overwrite mocks when many patterns map to the + same file. * Improved printing of skipped tests in verbose mode. * Improved resolution code in jest-resolve. -* Improved to only show patch marks in assertion errors when the comparison results in large objects. +* Improved to only show patch marks in assertion errors when the comparison + results in large objects. * New `--collectCoverageFrom` cli argument. * New `--coverageDirectory` cli argument. -* New `expect.addSnapshotSerializer` to add custom snapshot serializers for tests. +* New `expect.addSnapshotSerializer` to add custom snapshot serializers for + tests. * New `jest.spyOn`. * New `testMatch` configuration option that accepts glob patterns. -* New eslint-plugin-jest with no-disabled-tests, no-focuses-tests and no-identical-title rules and default configuration and globals. +* New eslint-plugin-jest with no-disabled-tests, no-focuses-tests and + no-identical-title rules and default configuration and globals. * New expect.stringContaining asymmetric matcher. -* New feature to make manual mocks with nested folders work. For example `__mocks__/react-native/Library/Text.js` will now work as expected. +* New feature to make manual mocks with nested folders work. For example + `__mocks__/react-native/Library/Text.js` will now work as expected. * New feature to re-run tests through the notification when using `--notify`. * New jest-phabricator package to integrate Jest code coverage in phabriactor. -* New jest-validate package to improve configuration errors, help with suggestions of correct configuration and to be adopted in other libraries. +* New jest-validate package to improve configuration errors, help with + suggestions of correct configuration and to be adopted in other libraries. * New pretty-printing for asymmetric matchers. * New RSS feed for Jest's blog. * New way to provide a reducer to extract haste module ids. * New website, new documentation, new color scheme and new homepage. -* Rewritten watch mode for instant feedback, better code quality and to build new features on top of it (#2362). +* Rewritten watch mode for instant feedback, better code quality and to build + new features on top of it (#2362). ## jest 18.1.0 * Fixed console.log and fake timer behavior in node 7.3. * Updated istanbul-api. * Updated jest-diff equality error message. -* Disabled arrow keys when entering a pattern in watch mode to prevent broken behavior. Will be improved in a future release. -* Moved asymmetric matchers and equality functionality from Jasmine into jest-matchers. +* Disabled arrow keys when entering a pattern in watch mode to prevent broken + behavior. Will be improved in a future release. +* Moved asymmetric matchers and equality functionality from Jasmine into + jest-matchers. * Removed jasmine and jest-snapshot dependency from jest-matchers. * Removed unused global `context` variable. * Show a better error message if the config is invalid JSON. @@ -446,33 +776,40 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html -* The testResultsProcessor function is now required to return the modified results. +* The testResultsProcessor function is now required to return the modified + results. * Removed `pit` and `mockImpl`. Use `it` or `mockImplementation` instead. * Fixed re-running tests when `--bail` is used together with `--watch`. * `pretty-format` is now merged into Jest. * `require('v8')` now works properly in a test context. * Jest now clears the entire scrollback in watch mode. -* Added `expect.any`, `expect.anything`, `expect.objectContaining`, `expect.arrayContaining`, `expect.stringMatching`. -* Properly resolve `snapshotSerializers`, `setupFiles`, `transform`, `testRunner` and `testResultsProcessor` instead of using `path.resolve`. +* Added `expect.any`, `expect.anything`, `expect.objectContaining`, + `expect.arrayContaining`, `expect.stringMatching`. +* Properly resolve `snapshotSerializers`, `setupFiles`, `transform`, + `testRunner` and `testResultsProcessor` instead of using `path.resolve`. * `--testResultsProcessor` is now exposed through the cli. * Renamed `--jsonOutputFile` to `--outputFile`. * Added `jest-editor-support` for vscode and Nuclide integration. * Fixed `test.concurrent` unhandled promise rejections. * The Jest website is now auto-deployed when merging into master. * Updated `testRegex` to include `test.js` and `spec.js` files. -* Fixes for `babel-plugin-jest-hoist` when using `jest.mock` with three arguments. -* The `JSON` global in `jest-environment-node` now comes from the vm context instead of the parent context. +* Fixes for `babel-plugin-jest-hoist` when using `jest.mock` with three + arguments. +* The `JSON` global in `jest-environment-node` now comes from the vm context + instead of the parent context. * Jest does not print stack traces from babel any longer. * Fake timers are reset when `FakeTimers.useTimers()` is called. * Usage of Jest in watch mode can be hidden through `JEST_HIDE_USAGE`. -* Added `expect.assertions(number)` which will ensure that a specified amount of assertions is made in one test. +* Added `expect.assertions(number)` which will ensure that a specified amount of + assertions is made in one test. * Added `.toMatchSnapshot(?string)` feature to give snapshots a name. * Escape regex in snapshots. * `jest-react-native` was deprecated and now forwards `react-native`. * Added `.toMatchObject` matcher. * Further improve printing of large objects. * Fixed `NaN% Failed` in the OS notification when using `--notify`. -* The first test run without cached timings will now use separate processes instead of running in band. +* The first test run without cached timings will now use separate processes + instead of running in band. * Added `.toHaveProperty` matcher. * Fixed `Map`/`Set` comparisons. * `test.concurrent` now works with `--testNamePattern`. @@ -498,7 +835,8 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * Properly resolve modules with platform extensions on react-native. * Added support for custom snapshots serializers. * Updated to Jasmine 2.5.2. -* Big diffs are now collapsed by default in snapshots and assertions. Added `--expand` (or `-e`) to show the full diff. +* Big diffs are now collapsed by default in snapshots and assertions. Added + `--expand` (or `-e`) to show the full diff. * Replaced `scriptPreprocessor` with the new `transform` option. * Added `jest.resetAllMocks` which replaces `jest.clearAllMocks`. * Fixes for react-native preset. @@ -523,33 +861,42 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest 16.0.0 * Previously failed tests are now always run first. -* A new concurrent reporter shows currently running tests, a test summary, a progress bar and estimated remaining time if possible. +* A new concurrent reporter shows currently running tests, a test summary, a + progress bar and estimated remaining time if possible. * Improved CLI colors. * `jest ` is now case-insensitive. * Added `it.only`, `it.skip`, `test.only`, `test.skip` and `xtest`. -* Added `--testNamePattern=pattern` or `-t ` to run individual tests in test files. +* Added `--testNamePattern=pattern` or `-t ` to run individual tests in + test files. * Jest now warns for duplicate mock files. -* Pressing `a`, `o`, `p`, `q` or `enter` while tests are running in the watch mode, the test run will be interrupted. +* Pressing `a`, `o`, `p`, `q` or `enter` while tests are running in the watch + mode, the test run will be interrupted. * `--bail` now works together with `--watch`. * Added `test.concurrent` for concurrent async tests. * Jest now automatically considers files and tests with the `.jsx` extension. * Added `jest.clearAllMocks` to clear all mocks manually. -* Rewrote Jest's snapshot implementation. `jest-snapshot` can now be more easily integrated into other test runners and used in other projects. - * This requires most snapshots to be updated when upgrading Jest. - * Objects and Arrays in snapshots are now printed with a trailing comma. - * Function names are not printed in snapshots any longer to reduce issues with code coverage instrumentation and different Node versions. - * Snapshots are now sorted using natural sort order. - * Snapshots are not marked as obsolete any longer when using `fit` or when an error is thrown in a test. +* Rewrote Jest's snapshot implementation. `jest-snapshot` can now be more easily + integrated into other test runners and used in other projects. +* This requires most snapshots to be updated when upgrading Jest. +* Objects and Arrays in snapshots are now printed with a trailing comma. +* Function names are not printed in snapshots any longer to reduce issues with + code coverage instrumentation and different Node versions. +* Snapshots are now sorted using natural sort order. +* Snapshots are not marked as obsolete any longer when using `fit` or when an + error is thrown in a test. * Finished migration of Jasmine matchers to the new Jest matchers. - * Pretty print `toHaveBeenLastCalledWith`, `toHaveBeenCalledWith`, `lastCalledWith` and `toBeCalledWith` failure messages. - * Added `toBeInstanceOf` matcher. - * Added `toContainEqual` matcher. - * Added `toThrowErrorMatchingSnapshot` matcher. +* Pretty print `toHaveBeenLastCalledWith`, `toHaveBeenCalledWith`, + `lastCalledWith` and `toBeCalledWith` failure messages. +* Added `toBeInstanceOf` matcher. +* Added `toContainEqual` matcher. +* Added `toThrowErrorMatchingSnapshot` matcher. * Improved `moduleNameMapper` resolution. * Module registry fixes. -* Fixed invocation of the `setupTestFrameworkScriptFile` script to make it easier to use chai together with Jest. +* Fixed invocation of the `setupTestFrameworkScriptFile` script to make it + easier to use chai together with Jest. * Removed react-native special case in Jest's configuration. -* Added `--findRelatedTests ` cli option to run tests related to the specified files. +* Added `--findRelatedTests ` cli option to run tests related to + the specified files. * Added `jest.deepUnmock` to `babel-plugin-jest-hoist`. * Added `jest.runTimersToTime` which is useful together with fake timers. * Improved automated mocks for ES modules compiled with babel. @@ -565,7 +912,8 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * Pretty printer updates for React and global window objects. * `jest-runtime` overwrites automocking from configuration files. * Improvements for watch mode on Windows. -* afterAll/afterEach/beforeAll/beforeEach can now return a Promise and be used together with async/await. +* afterAll/afterEach/beforeAll/beforeEach can now return a Promise and be used + together with async/await. * Improved stack trace printing on Node 4. ## jest 15.0.2 @@ -582,23 +930,30 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest 15.0.0 * See https://facebook.github.io/jest/blog/2016/09/01/jest-15.html -* Jest by default now also recognizes files ending in `.spec.js` and `.test.js` as test files. +* Jest by default now also recognizes files ending in `.spec.js` and `.test.js` + as test files. * Completely replaced most Jasmine matchers with new Jest matchers. * Rewrote Jest's CLI output for test failures and summaries. * Added `--env` option to override the default test environment. -* Disabled automocking, fake timers and resetting the module registry by default. -* Added `--watchAll`, made `--watch` interactive and added the ability to update snapshots and select test patterns in watch mode. +* Disabled automocking, fake timers and resetting the module registry by + default. +* Added `--watchAll`, made `--watch` interactive and added the ability to update + snapshots and select test patterns in watch mode. * Jest uses verbose mode when running a single test file. * Console messages are now buffered and printed along with the test results. -* Fix `testEnvironment` resolution to prefer `jest-environment-{name}` instead of `{name}` only. This prevents a module colision when using `jsdom` as test environment. +* Fix `testEnvironment` resolution to prefer `jest-environment-{name}` instead + of `{name}` only. This prevents a module colision when using `jsdom` as test + environment. * `moduleNameMapper` now uses a resolution algorithm. * Improved performance for small test runs. * Improved API documentation. * Jest now works properly with directories that have special characters in them. -* Improvements to Jest's own test infra by merging integration and unit tests. Code coverage is now collected for Jest. +* Improvements to Jest's own test infra by merging integration and unit tests. + Code coverage is now collected for Jest. * Added `global.global` to the node environment. * Fixed babel-jest-plugin-hoist issues with functions called `mock`. -* Improved jest-react-native preset with mocks for ListView, TextInput, ActivityIndicator and ScrollView. +* Improved jest-react-native preset with mocks for ListView, TextInput, + ActivityIndicator and ScrollView. * Added `collectCoverageFrom` to collect code coverage from untested files. * Rewritten code coverage support. @@ -623,10 +978,10 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest 14.0.0 * Official release of snapshot tests. -* Started to replace Jasmine matchers with Jest matchers: `toBe`, - `toBeFalsy`, `toBeTruthy`, `toBeNaN`, - `toBe{Greater,Less}Than{,OrEqual}`, `toBeNull`, `toBeDefined`, - `toBeUndefined`, `toContain`, `toMatch`, `toBeCloseTo` were rewritten. +* Started to replace Jasmine matchers with Jest matchers: `toBe`, `toBeFalsy`, + `toBeTruthy`, `toBeNaN`, `toBe{Greater,Less}Than{,OrEqual}`, `toBeNull`, + `toBeDefined`, `toBeUndefined`, `toContain`, `toMatch`, `toBeCloseTo` were + rewritten. * Rewrite of Jest's reporters. * Experimental react-native support. * Removed Jasmine 1 support from Jest. @@ -644,8 +999,7 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * Fixed printing of "JSX objects" in snapshots. * Fixes for `--verbose` option and top level `it` calls. * Extended the node environment with more globals. -* testcheck now needs to be required explicitly through - `require('jest-check')`. +* testcheck now needs to be required explicitly through `require('jest-check')`. * Added `jest.deepUnmock`. * Fail test suite if it does not contain any tests. @@ -656,17 +1010,17 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html browser field in `package.json` if you are writing tests for client side apps * Added `jest-repl`. * Split up `jest-cli` into `jest-runtime` and `jest-config`. -* Added a notification plugin that shows a test run notification - using `--notify`. -* Refactored `TestRunner` into `SearchSource` and improved the - "no tests found" message. +* Added a notification plugin that shows a test run notification using + `--notify`. +* Refactored `TestRunner` into `SearchSource` and improved the "no tests found" + message. * Added `jest.isMockFunction(jest.fn())` to test for mock functions. -* Improved test reporter printing and added a test failure summary when - running many tests. +* Improved test reporter printing and added a test failure summary when running + many tests. * Add support for property testing via testcheck-js. * Added a webpack tutorial. -* Added support for virtual mocks through - `jest.mock('Module', implementation, {virtual: true})`. +* Added support for virtual mocks through `jest.mock('Module', implementation, + {virtual: true})`. * Added snapshot functionality through `toMatchSnapshot()`. * Redesigned website. @@ -684,10 +1038,11 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * `it` can now return a Promise for async testing. `pit` was deprecated. * Added `jest-resolve` as a standalone package based on the Facebook module resolution algorithm. -* Added `jest-changed-files` as a standalone package to detect changed files - in a git or hg repo. +* Added `jest-changed-files` as a standalone package to detect changed files in + a git or hg repo. * Added `--setupTestFrameworkFile` to cli. -* Added support for coverage thresholds. See http://facebook.github.io/jest/docs/api.html#coveragethreshold-object. +* Added support for coverage thresholds. See + http://facebook.github.io/jest/docs/api.html#coveragethreshold-object. * Updated to jsdom 9.0. * Updated and improved stack trace reporting. * Added `module.filename` and removed the invalid `module.__filename` field. @@ -751,8 +1106,8 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * Clear the terminal window when using `--watch`. * By default, `--watch` will now only runs tests related to changed files. `--watch=all` can be used to run all tests on file system changes. -* Debounce `--watch` re-runs to not trigger test runs during a - branch switch in version control. +* Debounce `--watch` re-runs to not trigger test runs during a branch switch in + version control. * Added `jest.fn()` and `jest.fn(implementation)` as convenient shorcuts for `jest.genMockFunction()` and `jest.genMockFunction().mockImplementation()`. * Added an `automock` option to turn off automocking globally. @@ -775,8 +1130,8 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * Removed `preprocessCachingDisabled` config option. * Added a `testEnvironment` option to customize the sandbox environment. * Added support for `@scoped/name` npm packages. -* Added an integration test runner for Jest that runs all tests for examples - and packages. +* Added an integration test runner for Jest that runs all tests for examples and + packages. ## 0.8.2 @@ -804,16 +1159,17 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## 0.7.0 -* Fixed a memory leak with test contexts. Jest now properly cleans up - test environments after each test. Added `--logHeapUsage` to log memory - usage after each test. Note: this is option is meant for debugging memory - leaks and might significantly slow down your test run. +* Fixed a memory leak with test contexts. Jest now properly cleans up test + environments after each test. Added `--logHeapUsage` to log memory usage after + each test. Note: this is option is meant for debugging memory leaks and might + significantly slow down your test run. * Removed `mock-modules`, `node-haste` and `mocks` virtual modules. This is a breaking change of undocumented public API. Usage of this API can safely be automatically updated through an automated codemod: - * Example: http://astexplorer.net/#/zrybZ6UvRA - * Codemod: https://github.com/cpojer/js-codemod/blob/master/transforms/jest-update.js - * jscodeshift: https://github.com/facebook/jscodeshift +* Example: http://astexplorer.net/#/zrybZ6UvRA +* Codemod: + https://github.com/cpojer/js-codemod/blob/master/transforms/jest-update.js +* jscodeshift: https://github.com/facebook/jscodeshift * Removed `navigator.onLine` and `mockSetReadOnlyProperty` from the global jsdom environment. Use `window.navigator.onLine = true;` in your test setup and `Object.defineProperty` instead. @@ -821,8 +1177,8 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## 0.6.1 * Updated jsdom to 7.0.2. -* Use the current working directory as root when passing a jest config from - the command line. +* Use the current working directory as root when passing a jest config from the + command line. * Updated the React examples and getting started guide * Modules now receive a `module.parent` field so unmocked modules don't assume they are run directly any longer. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 8cb7a2b38da1..00e67a2fad81 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,10 +1,17 @@ # Contributing to Jest -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. +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. ## [Code of Conduct](https://code.facebook.com/codeofconduct) -Facebook has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) so that you can understand what actions will and will not be tolerated. +Facebook has adopted a Code of Conduct that we expect project participants to +adhere to. Please read [the full text](https://code.facebook.com/codeofconduct) +so that you can understand what actions will and will not be tolerated. ## Our Development Process @@ -12,45 +19,55 @@ The core team works directly on GitHub and all work is public. ### `master` is unsafe -We will do our best to keep `master` in good shape, with tests passing at all times. But in order to move fast, we will make API changes that your application might not be compatible with. We will do our best to communicate these changes and always version appropriately so you can lock into a specific version if need be. +We will do our best to keep `master` in good shape, with tests passing at all +times. But in order to move fast, we will make API changes that your application +might not be compatible with. We will do our best to communicate these changes +and always version appropriately so you can lock into a specific version if need +be. ### Workflow and Pull Requests -The core team will be monitoring for pull requests. When we get one, we'll run some Facebook-specific integration tests on it first. From here, we'll need to get another person to sign off on the changes and then merge the pull request. For API changes we may need to fix internal uses, which could cause some delay. We'll do our best to provide updates and feedback throughout the process. +The core team will be monitoring for pull requests. When we get one, we'll run +some Facebook-specific integration tests on it first. From here, we'll need to +get another person to sign off on the changes and then merge the pull request. +For API changes we may need to fix internal uses, which could cause some delay. +We'll do our best to provide updates and feedback throughout the process. -*Before* submitting a pull request, please make sure the following is done… +_Before_ submitting a pull request, please make sure the following is done… -1. Fork the repo and create your branch from `master`. - A guide on how to fork a repository: https://help.github.com/articles/fork-a-repo/ +1. Fork the repo and create your branch from `master`. A guide on how to fork a + repository: https://help.github.com/articles/fork-a-repo/ Open terminal (e.g. Terminal, iTerm, Git Bash or Git Shell) and type: + ```sh git clone https://github.com//jest cd jest git checkout -b my_branch ``` - Note: - Replace `` with your GitHub username -2. Jest uses [Yarn](https://code.facebook.com/posts/1840075619545360) - for running development scripts. If you haven't already done so, - please [install yarn](https://yarnpkg.com/en/docs/install). + Note: Replace `` with your GitHub username + +2. Jest uses [Yarn](https://code.facebook.com/posts/1840075619545360) for + running development scripts. If you haven't already done so, please + [install yarn](https://yarnpkg.com/en/docs/install). + +3. Run `yarn install`. On Windows: To install + [Yarn](https://yarnpkg.com/en/docs/install#windows-tab) on Windows you may + need to download either node.js or Chocolatey
+ + ```sh + yarn install + ``` -3. Run `yarn install`. - On Windows: - To install [Yarn](https://yarnpkg.com/en/docs/install#windows-tab) on Windows you may need to download either node.js or Chocolatey
+ To check your version of Yarn and ensure it's installed you can type: - ```sh - yarn install - ``` - To check your version of Yarn and ensure it's installed you can type: - ```sh - yarn --version - ``` + ```sh + yarn --version + ``` -4. If you've added code that should be tested, add tests. You - can use watch mode that continuously transforms changed files - to make your life easier. +4. If you've added code that should be tested, add tests. You can use watch mode + that continuously transforms changed files to make your life easier. ```sh # in the background @@ -59,9 +76,9 @@ The core team will be monitoring for pull requests. When we get one, we'll run s 5. If you've changed APIs, update the documentation. -6. Ensure the test suite passes via `yarn test`. To run the test suite you - may need to install Mercurial (`hg`). On macOS, this can be done - using [homebrew](http://brew.sh/): `brew install hg`. +6. Ensure the test suite passes via `yarn test`. To run the test suite you may + need to install Mercurial (`hg`). On macOS, this can be done using + [homebrew](http://brew.sh/): `brew install hg`. ```sh brew install hg # maybe @@ -72,12 +89,13 @@ The core team will be monitoring for pull requests. When we get one, we'll run s #### Additional Workflow for any changes made to website or docs -If you are making changes to the website or documentation, test the website folder -and run the server to check if your changes are being displayed accurately. +If you are making changes to the website or documentation, test the website +folder and run the server to check if your changes are being displayed +accurately. 1. Locate to the website directory and install any website specific dependencies - by typing in `yarn`. Following steps are to be followed - for this purpose from the root directory. + by typing in `yarn`. Following steps are to be followed for this purpose from + the root directory. ```sh cd website # Only needed if you are not already in the website directory yarn @@ -88,13 +106,18 @@ and run the server to check if your changes are being displayed accurately. ### Contributor License Agreement (CLA) -In order to accept your pull request, we need you to submit a CLA. You only need to do this once, so if you've done this for another Facebook open source project, you're good to go. If you are submitting a pull request for the first time, just let us know that you have completed the CLA and we can cross-check with your GitHub username. +In order to accept your pull request, we need you to submit a CLA. You only need +to do this once, so if you've done this for another Facebook open source +project, you're good to go. If you are submitting a pull request for the first +time, just let us know that you have completed the CLA and we can cross-check +with your GitHub username. [Complete your CLA here.](https://code.facebook.com/cla) ## How to try a development build of Jest in another project -To link `jest` on the command line to `jest-cli/bin/jest.js` in a development build: +To link `jest` on the command line to `jest-cli/bin/jest.js` in a development +build: ```sh cd /path/to/your/Jest_clone/packages/jest-cli @@ -122,9 +145,11 @@ cd /path/to/another/project jest [options] # run jest-cli/bin/jest.js in the development build ``` -* To decide whether to specify any options, see `test` under `scripts` in the `package.json` file of the other project. +* To decide whether to specify any options, see `test` under `scripts` in the + `package.json` file of the other project. -To unlink `jest` on the command line from `jest-cli/bin/jest.js` in a development build: +To unlink `jest` on the command line from `jest-cli/bin/jest.js` in a +development build: ```sh yarn unlink jest-cli @@ -134,19 +159,26 @@ yarn unlink jest-cli ### Where to Find Known Issues -We will be using GitHub Issues for our public bugs. We will keep a close eye on this and try to make it clear when we have an internal fix in progress. Before filing a new issue, try to make sure your problem doesn't already exist. +We will be using GitHub Issues for our public bugs. We will keep a close eye on +this and try to make it clear when we have an internal fix in progress. Before +filing a new issue, try to make sure your problem doesn't already exist. ### Reporting New Issues -The best way to get your bug fixed is to provide a reduced test case. Please provide a public repository with a runnable example. +The best way to get your bug fixed is to provide a reduced test case. Please +provide a public repository with a runnable example. ### Security Bugs -Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe disclosure of security bugs. With that in mind, please do not file public issues; go through the process outlined on that page. +Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe +disclosure of security bugs. With that in mind, please do not file public +issues; go through the process outlined on that page. ## How to Get in Touch -* Discord - [#jest](https://discordapp.com/channels/102860784329052160/103622435865104384) on [Reactiflux](http://www.reactiflux.com/) +* Discord - + [#jest](https://discordapp.com/channels/102860784329052160/103622435865104384) + on [Reactiflux](http://www.reactiflux.com/) ## Code Conventions @@ -161,4 +193,5 @@ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe ## License -By contributing to Jest, you agree that your contributions will be licensed under its MIT license. +By contributing to Jest, you agree that your contributions will be licensed +under its MIT license. diff --git a/docs/CLI.md b/docs/CLI.md index 716948ee24d8..f2d0b6a03054 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -3,49 +3,61 @@ 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. +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). +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. +Watch mode also enables to specify the name or path to a file to focus on a +specific set of tests. ## 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: +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" @@ -57,7 +69,8 @@ you can use: npm test -- -u -t="ColorPicker" ``` -CLI options take precedence over values from the [Configuration](Configuration.md). +CLI options take precedence over values from the +[Configuration](Configuration.md). ## Options @@ -69,7 +82,11 @@ CLI options take precedence over values from the [Configuration](Configuration.m ### `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. Note: depending on your terminal, you may need to quote this argument: `jest "my.*(complex)?pattern"`. +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. Note: depending on your terminal, you may need to quote +this argument: `jest "my.*(complex)?pattern"`. ### `--bail` @@ -77,21 +94,34 @@ Alias: `-b`. Exit the test suite immediately upon the first failing test suite. ### `--cache` -Whether to use the cache. Defaults to true. Disable the cache using `--no-cache`. *Note: 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.* +Whether to use the cache. Defaults to true. Disable the cache using +`--no-cache`. _Note: 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`. +If you want to inspect the cache, use `--showConfig` and look at the +`cacheDirectory` value. If you need to clear the cache, use `--clearCache`. ### `--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`. +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` -### `--clearCache` ##### available in Jest **21.3.0+** -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`. *Note: clearing the cache will reduce performance.* + +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`. _Note: clearing the cache will reduce performance._ ### `--collectCoverageFrom=` -Relative to the root directory, glob pattern matching the files that coverage info needs to be collected from. +Relative to the root directory, glob pattern matching the files that coverage +info needs to be collected from. ### `--colors` @@ -99,11 +129,15 @@ Forces test results output highlighting even if stdout is not a TTY. ### `--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 current directory is assumed to be the rootDir for the project. This can also be a JSON-encoded value which Jest will use as configuration. +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 current directory is assumed to +be the rootDir for the project. This can also be a JSON-encoded value which Jest +will use as configuration. ### `--coverage` -Indicates that test coverage information should be collected and reported in the output. +Indicates that test coverage information should be collected and reported in the +output. ### `--debug` @@ -111,7 +145,8 @@ Print debugging info about your Jest config. ### `--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`. +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`. ### `--expand` @@ -119,11 +154,18 @@ Alias: `-e`. Use this flag to show full diffs and errors instead of a patch. ### `--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. +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. ### `--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. *Note: 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.* +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. _Note: 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._ ### `--help` @@ -131,7 +173,8 @@ Show the help information, similar to this page. ### `--json` -Prints the test results in JSON. This mode will send all other test output and user messages to stderr. +Prints the test results in JSON. This mode will send all other test output and +user messages to stderr. ### `--outputFile=` @@ -143,15 +186,21 @@ Will run all tests affected by file changes in the last commit made. ### `--listTests` -Lists all tests as JSON that Jest will run given the arguments, and exits. This can be used together with `--findRelatedTests` to know which tests Jest will run. +Lists all tests as JSON that Jest will run given the arguments, and exits. This +can be used together with `--findRelatedTests` to know which tests Jest will +run. ### `--logHeapUsage` -Logs the heap usage after every test. Useful to debug memory leaks. Use together with `--runInBand` and `--expose-gc` in node. +Logs the heap usage after every test. Useful to debug memory leaks. Use together +with `--runInBand` and `--expose-gc` in node. ### `--maxWorkers=` -Alias: `-w`. Specifies the maximum number of workers the worker-pool will spawn for running tests. This defaults to the number of the cores available on your machine. It may be useful to adjust this in resource limited environments like CIs but the default should be adequate for most use-cases. +Alias: `-w`. Specifies the maximum number of workers the worker-pool will spawn +for running tests. This defaults to the number of the cores available on your +machine. It may be useful to adjust this in resource limited environments like +CIs but the default should be adequate for most use-cases. ### `--noStackTrace` @@ -159,11 +208,15 @@ 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. +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). +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). ### `--projects ... ` @@ -171,11 +224,15 @@ Run tests from one or more projects. ### `--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. +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. ### `--setupTestFrameworkScriptFile=` -The path to a module that runs some code to configure or set up the testing framework before each test. Beware that files imported by the setup script will not be mocked during testing. +The path to a module that runs some code to configure or set up the testing +framework before each test. Beware that files imported by the setup script will +not be mocked during testing. ### `--showConfig` @@ -187,11 +244,15 @@ Prevent tests from printing messages through the console. ### `--testNamePattern=` -Alias: `-t`. Run only tests and test suites 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`. +Alias: `-t`. Run only tests and test suites 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`. ### `--testLocationInResults` -Adds a `location` field to test results. Useful if you want to report the location of a test in a reporter. +Adds a `location` field to test results. Useful if you want to report the +location of a test in a reporter. Note that `column` is 0-indexed while `line` is not. @@ -200,11 +261,12 @@ Note that `column` is 0-indexed while `line` is not. "column": 4, "line": 5 } -``` +``` ### `--testPathPattern=` -A regexp pattern string that is matched against all tests paths before executing the test. +A regexp pattern string that is matched against all tests paths before executing +the test. ### `--testRunner=` @@ -212,7 +274,9 @@ Lets you specify a custom test runner. ### `--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. +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` @@ -228,12 +292,16 @@ 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. +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. ### `--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. +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. ### `--watchman` -Whether to use watchman for file crawling. Defaults to true. Disable using `--no-watchman`. +Whether to use watchman for file crawling. Defaults to true. Disable using +`--no-watchman`. diff --git a/docs/Configuration.md b/docs/Configuration.md index d4f2adc8fb51..f6ecc1a9d8a0 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -3,10 +3,11 @@ 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: +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 { @@ -39,90 +40,145 @@ When using the --config option, the JSON file must not contain a "jest" key: ## 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. +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. ------ +--- ## Reference ### `automock` [boolean] + Default: `false` -This option is disabled by default. If you are introducing Jest to a large organization with an existing codebase but few tests, enabling this option can be helpful to introduce unit tests gradually. Modules can be explicitly auto-mocked using `jest.mock(moduleName)`. +This option is disabled by default. If you are introducing Jest to a large +organization with an existing codebase but few tests, enabling this option can +be helpful to introduce unit tests gradually. Modules can be explicitly +auto-mocked using `jest.mock(moduleName)`. -*Note: Core modules, like `fs`, are not mocked by default. They can be mocked explicitly, like `jest.mock('fs')`.* +_Note: Core modules, like `fs`, are not mocked by default. They can be mocked +explicitly, like `jest.mock('fs')`._ -*Note: Automocking has a performance cost most noticeable in large projects. See [here](troubleshooting.html#tests-are-slow-when-leveraging-automocking) for details and a workaround.* +_Note: Automocking has a performance cost most noticeable in large projects. See +[here](troubleshooting.html#tests-are-slow-when-leveraging-automocking) for +details and a workaround._ ### `browser` [boolean] + Default: `false` -Respect Browserify's [`"browser"` field](https://github.com/substack/browserify-handbook#browser-field) in `package.json` when resolving modules. Some modules export different versions based on whether they are operating in Node or a browser. +Respect Browserify's +[`"browser"` field](https://github.com/substack/browserify-handbook#browser-field) +in `package.json` when resolving modules. Some modules export different versions +based on whether they are operating in Node or a browser. ### `bail` [boolean] + Default: `false` -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 the first failure. +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 the first failure. ### `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 raking that needs to happen while running tests. This config option lets you customize where Jest stores that cache data on disk. +Jest attempts to scan your dependency tree once (up-front) and cache it in order +to ease some of the filesystem raking that needs to happen while running tests. +This config option lets you customize where Jest stores that cache data on disk. ### `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. +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. ### `collectCoverageFrom` [array] + Default: `undefined` An array of [glob patterns](https://github.com/jonschlinkert/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. +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/**"] + "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/**`. +This will collect coverage information for all the files inside the project's +`rootDir`, except the ones that match `**/node_modules/**` or `**/vendor/**`. -*Note: This option requires `collectCoverage` to be set to true or Jest to be invoked with `--coverage`.* +_Note: This option requires `collectCoverage` to be set to true or Jest to be +invoked with `--coverage`._ ### `coverageDirectory` [string] + Default: `undefined` The directory where Jest should output its coverage files. ### `coveragePathIgnorePatterns` [array] + 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. +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/"]`. +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/"]`. ### `coverageReporters` [array] + Default: `["json", "lcov", "text"]` -A list of reporter names that Jest uses when writing coverage reports. Any [istanbul reporter](https://github.com/gotwarlost/istanbul/tree/master/lib/report) can be used. +A list of reporter names that Jest uses when writing coverage reports. Any +[istanbul reporter](https://github.com/gotwarlost/istanbul/tree/master/lib/report) +can be used. -*Note: Setting this option overwrites the default values. Add `"text"` or `"text-summary"` to see a coverage summary in the console output.* +_Note: Setting this option overwrites the default values. Add `"text"` or +`"text-summary"` to see a coverage summary in the console output._ ### `coverageThreshold` [object] -Default: `undefined` -This will be used to configure minimum threshold enforcement for coverage results. If the thresholds are not met, jest will return failure. Thresholds, when specified as a positive number are taken to be the minimum percentage required. When a threshold is specified as a negative number it represents the maximum number of uncovered entities allowed. Thresholds can be specified as `global`, as `glob` paths or just paths. 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. Threshold for globs is applied to all files matching the glob. If the file specified by path is not found, error is returned. +Default: `undefined` -For example, statements: 90 implies minimum statement coverage is 90%. statements: -10 implies that no more than 10 uncovered statements are allowed. `global` branch threshold 50 will be applied to all files minus matching `./src/components/**/*.js` and `./src/api/very-important-module.js`. +This will be used to configure minimum threshold enforcement for coverage +results. If the thresholds are not met, jest will return failure. Thresholds, +when specified as a positive number are taken to be the minimum percentage +required. When a threshold is specified as a negative number it represents the +maximum number of uncovered entities allowed. Thresholds can be specified as +`global`, as `glob` paths or just paths. 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. Threshold for +globs is applied to all files matching the glob. If the file specified by path +is not found, error is returned. + +For example, statements: 90 implies minimum statement coverage is 90%. +statements: -10 implies that no more than 10 uncovered statements are allowed. +`global` branch threshold 50 will be applied to all files minus matching +`./src/components/**/*.js` and `./src/api/very-important-module.js`. ```json { @@ -151,11 +207,13 @@ For example, statements: 90 implies minimum statement coverage is 90%. statement ``` ### `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: +For example, the following would create a global `__DEV__` variable set to +`true` in all test environments: ```json { @@ -168,7 +226,9 @@ For example, the following would create a global `__DEV__` variable set to `true } ``` -Note that, 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. +Note that, 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. ### `mapCoverage` [boolean] @@ -176,9 +236,20 @@ Note that, if you specify a global reference value (like an object or array) her Default: `false` -If you have [transformers](#transform-object-string-string) configured that emit source maps, Jest will use them to try and map code coverage against the original source code when writing [reports](#coveragereporters-array-string) and checking [thresholds](#coveragethreshold-object). This is done on a best-effort basis as some compile-to-JavaScript languages may provide more accurate source maps than others. This can also be resource-intensive. If Jest is taking a long time to calculate coverage at the end of a test run, try setting this option to `false`. - -Both inline source maps and source maps returned directly from a transformer are supported. Source map URLs are not supported because Jest may not be able to locate them. To return source maps from a transformer, the `process` function can return an object like the following. The `map` property may either be the source map object, or the source map object as a JSON string. +If you have [transformers](#transform-object-string-string) configured that emit +source maps, Jest will use them to try and map code coverage against the +original source code when writing [reports](#coveragereporters-array-string) and +checking [thresholds](#coveragethreshold-object). This is done on a best-effort +basis as some compile-to-JavaScript languages may provide more accurate source +maps than others. This can also be resource-intensive. If Jest is taking a long +time to calculate coverage at the end of a test run, try setting this option to +`false`. + +Both inline source maps and source maps returned directly from a transformer are +supported. Source map URLs are not supported because Jest may not be able to +locate them. To return source maps from a transformer, the `process` function +can return an object like the following. The `map` property may either be the +source map object, or the source map object as a JSON string. ```js return { @@ -188,115 +259,153 @@ return { ``` ### `moduleFileExtensions` [array] + Default: `["js", "json", "jsx", "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. +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. -If you are using TypeScript this should be `["js", "jsx", "json", "ts", "tsx"]`, check [ts-jest's documentation](https://github.com/kulshekhar/ts-jest). +If you are using TypeScript this should be `["js", "jsx", "json", "ts", "tsx"]`, +check [ts-jest's documentation](https://github.com/kulshekhar/ts-jest). ### `moduleDirectories` [array] + 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"]` +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"]` ### `moduleNameMapper` [object] + Default: `null` -A map from regular expressions to module names that allow to stub out resources, like images or styles with a single module. +A map from regular expressions to 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. +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. +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. +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", + "^[./a-zA-Z0-9$_-]+\\.png$": "/RelativeImageStub.js", "module_name_(.*)": "/substituted_module_$1.js" } } ``` -*Note: If you provide module name 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.* + +_Note: If you provide module name 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] + 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. +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/"]`. +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] + 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/"]`. +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 notifications for test results. ### `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 exports a `jest-preset.json` module on its top level. +A preset that is used as a base for Jest's configuration. A preset should point +to an npm module that exports a `jest-preset.json` module on its top level. ### `projects` [array] + 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. +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/*" - ] + "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. +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. ### `clearMocks` [boolean] + Default: `false` -Automatically clear mock calls and instances between every test. Equivalent to calling `jest.clearAllMocks()` between each test. This does not remove any mock implementation that may have been provided. +Automatically clear mock calls and instances between every test. Equivalent to +calling `jest.clearAllMocks()` between each test. This does not remove any mock +implementation that may have been provided. ### `reporters` [array] + Default: `undefined` ##### available in Jest **20.0.0+** -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. +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. +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" - ] + "reporters": ["/my-custom-reporter.js"] } ``` -This will use custom reporter in addition to default reporters that Jest provides: +This will use custom reporter in addition to default reporters that Jest +provides: + ```json { - "reporters": [ - "default", - "/my-custom-reporter.js" - ] + "reporters": ["default", "/my-custom-reporter.js"] } ``` -Additionally, custom reporters can be configured by passing an `options` object as a second argument: +Additionally, custom reporters can be configured by passing an `options` object +as a second argument: + ```json { "reporters": [ @@ -306,9 +415,11 @@ Additionally, custom reporters can be configured by passing an `options` object } ``` -Custom reporter modules must define a class that takes a `GlobalConfig` and reporter options as constructor arguments: +Custom reporter modules must define a class that takes a `GlobalConfig` and +reporter options as constructor arguments: Example reporter: + ```js // my-custom-reporter.js class MyCustomReporter { @@ -327,7 +438,9 @@ class MyCustomReporter { module.exports = MyCustomReporter; ``` -Custom reporters can also force Jest to exit with non-0 code by returning an Error from `getLastError()` methods +Custom reporters can also force Jest to exit with non-0 code by returning an +Error from `getLastError()` methods + ```js class MyCustomReporter { // ... @@ -339,24 +452,37 @@ class MyCustomReporter { } ``` -For the full list of methods and argument types see `Reporter` type in [types/TestRunner.js](https://github.com/facebook/jest/blob/master/types/TestRunner.js) +For the full list of methods and argument types see `Reporter` type in +[types/TestRunner.js](https://github.com/facebook/jest/blob/master/types/TestRunner.js) ### `resetMocks` [boolean] + Default: `false` -Automatically reset mock state between every test. Equivalent to calling `jest.resetAllMocks()` between each test. This will lead to any mocks having their fake implementations removed but does not restore their initial implementation. +Automatically reset mock state between every test. Equivalent to calling +`jest.resetAllMocks()` between each test. This will lead to any mocks having +their fake implementations removed but does not restore their initial +implementation. ### `resetModules` [boolean] + Default: `false` -If enabled, the module registry for every test file will be reset before running each individual test. This is useful to isolate modules for every test so that local module state doesn't conflict between tests. This can be done programmatically using [`jest.resetModules()`](#jest-resetmodules). +If enabled, the module registry for every test file will be reset before running +each individual test. This is useful to isolate modules for every test so that +local module state doesn't conflict between tests. This can be done +programmatically using [`jest.resetModules()`](#jest-resetmodules). ### `resolver` [string] + Default: `undefined` ##### available in Jest **20.0.0+** -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: +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: ``` { @@ -369,52 +495,87 @@ This option allows the use of a custom resolver. This resolver must be a node mo } ``` -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. +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. ### `rootDir` [string] -Default: The root of the directory containing your jest's [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`. +Default: The root of the directory containing your jest's [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. +Oftentimes, you'll want to set this to `'src'` or `'lib'`, corresponding to +where in your repository the code is stored. -*Note that using `''` as a string token in any other path-based config settings will refer back to this value. So, for example, if you want your [`setupFiles`](#setupfiles-array) config entry to point at the `env-setup.js` file at the root of your project, you could set its value to `["/env-setup.js"]`.* +_Note that using `''` as a string token in any other path-based config +settings will refer back to this value. So, for example, if you want your +[`setupFiles`](#setupfiles-array) config entry to point at the `env-setup.js` +file at the root of your project, you could set its value to +`["/env-setup.js"]`._ ### `roots` [array] + 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. +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. -*Note: 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`).* +_Note: 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`)._ -*Note: 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/"]`.* +_Note: 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/"]`._ ### `setupFiles` [array] + Default: `[]` -The paths to modules that run some code to configure or set up the testing environment before each test. Since every test runs in its own environment, these scripts will be executed in the testing environment immediately before executing the test code itself. +The paths to modules that run some code to configure or set up the testing +environment before each test. Since every test runs in its own environment, +these scripts will be executed in the testing environment immediately before +executing the test code itself. -It's worth noting that this code will execute *before* [`setupTestFrameworkScriptFile`](#setuptestframeworkscriptfile-string). +It's worth noting that this code will execute _before_ +[`setupTestFrameworkScriptFile`](#setuptestframeworkscriptfile-string). ### `setupTestFrameworkScriptFile` [string] + Default: `undefined` -The path to a module that runs some code to configure or set up the testing framework before each test. 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. +The path to a module that runs some code to configure or set up the testing +framework before each test. 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. -For example, Jest ships with several plug-ins to `jasmine` that work by monkey-patching the jasmine API. If you wanted to add even more jasmine plugins to the mix (or if you wanted some custom, project-wide matchers for example), you could do so in this module. +For example, Jest ships with several plug-ins to `jasmine` that work by +monkey-patching the jasmine API. If you wanted to add even more jasmine plugins +to the mix (or if you wanted some custom, project-wide matchers for example), +you could do so in this module. ### `snapshotSerializers` [array] + 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. +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: @@ -428,7 +589,6 @@ module.exports = { test(val) { return val && val.hasOwnProperty('foo'); }, - }; ``` @@ -470,14 +630,23 @@ 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. +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. ### `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/tmpvar/jsdom). If you are building a node service, you can use the `node` option to use a node-like environment instead. +The test environment that will be used for testing. The default environment in +Jest is a browser-like environment through +[jsdom](https://github.com/tmpvar/jsdom). If you are building a node service, +you can use the `node` option to use a node-like environment instead. + +If some tests require another environment, you can add a `@jest-environment` +docblock. -If some tests require another environment, you can add a `@jest-environment` docblock. ##### available in Jest **20.0.0+** ```js @@ -491,10 +660,14 @@ 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 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. + ##### available in Jest **21.3.0+** -*Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown in their own TestEnvironment.* +_Note: TestEnvironment is sandboxed. Each test suite will trigger setup/teardown +in their own TestEnvironment._ Example: @@ -526,32 +699,41 @@ class CustomEnvironment extends NodeEnvironment { (default: `[ '**/__tests__/**/*.js?(x)', '**/?(*.)(spec|test).js?(x)' ]`) -The glob patterns Jest uses to detect test files. By default it looks for `.js` and `.jsx` 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`. +The glob patterns Jest uses to detect test files. By default it looks for `.js` +and `.jsx` 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/jonschlinkert/micromatch) package -for details of the patterns you can specify. +See the [micromatch](https://github.com/jonschlinkert/micromatch) package for +details of the patterns you can specify. -See also [`testRegex` [string]](#testregex-string), but note that you -cannot specify both options. +See also [`testRegex` [string]](#testregex-string), but note that you cannot +specify both options. ### `testPathIgnorePatterns` [array] + 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. +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/"]`. +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] + Default: `(/__tests__/.*|(\\.|/)(test|spec))\\.jsx?$` -The pattern Jest uses to detect test files. By default it looks for `.js` and `.jsx` 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]](#testmatch-array-string), but note -that you cannot specify both options. +The pattern Jest uses to detect test files. By default it looks for `.js` and +`.jsx` 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]](#testmatch-array-string), but note that you cannot +specify both options. The following is a visualization of the default regex: @@ -566,9 +748,12 @@ The following is a visualization of the default regex: ``` ### `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: +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: ``` { @@ -612,9 +797,12 @@ This option allows the use of a custom results processor. This processor must be ``` ### `testRunner` [string] + Default: `jasmine2` -This option allows 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. +This option allows 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: @@ -627,55 +815,103 @@ function testRunner( ): Promise ``` -An example of such function can be found in our default [jasmine2 test runner package](https://github.com/facebook/jest/blob/master/packages/jest-jasmine2/src/index.js). +An example of such function can be found in our default +[jasmine2 test runner package](https://github.com/facebook/jest/blob/master/packages/jest-jasmine2/src/index.js). ### `testURL` [string] + Default: `about:blank` -This option sets the URL for the jsdom environment. It is reflected in properties such as `location.href`. +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 `fake` allows the use of fake timers for functions such as `setTimeout`. Fake timers are useful when a piece of code sets a long timeout that we don't want to wait for in a test. +Setting this value to `fake` allows the use of fake timers for functions such as +`setTimeout`. Fake timers are useful when a piece of code sets a long timeout +that we don't want to wait for in a test. ### `transform` [object] -Default: `undefined` - -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 isn'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/master/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/) and [async-to-gen](http://github.com/leebyron/async-to-gen#jest). - -*Note: a transformer is only ran once per file unless the file has changed. During development of a transformer it can be useful to run Jest with `--no-cache` or to frequently [delete Jest's cache](Troubleshooting.md#caching-issues).* +Default: `undefined` -*Note: if you are using the `babel-jest` transformer and want to use an additional code preprocessor, keep in mind that when "transform" is overwritten in any way the `babel-jest` is not loaded automatically anymore. If you want to use it to compile JavaScript code it has to be explicitly defined. See [babel-jest plugin](https://github.com/facebook/jest/tree/master/packages/babel-jest#setup)* +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 isn'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/master/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/) and +[async-to-gen](http://github.com/leebyron/async-to-gen#jest). + +_Note: a transformer is only ran once per file unless the file has changed. +During development of a transformer it can be useful to run Jest with +`--no-cache` or to frequently +[delete Jest's cache](Troubleshooting.md#caching-issues)._ + +_Note: if you are using the `babel-jest` transformer and want to use an +additional code preprocessor, keep in mind that when "transform" is overwritten +in any way the `babel-jest` is not loaded automatically anymore. If you want to +use it to compile JavaScript code it has to be explicitly defined. See +[babel-jest plugin](https://github.com/facebook/jest/tree/master/packages/babel-jest#setup)_ ### `transformIgnorePatterns` [array] + Default: `["/node_modules/"]` -An array of regexp pattern strings that are matched against all source file paths before transformation. If the test path matches any of the patterns, it will not be transformed. +An array of regexp pattern strings that are matched against all source file +paths before transformation. If the test path matches any of the patterns, it +will not be transformed. -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: `["/bower_components/", "/node_modules/"]`. +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: `["/bower_components/", +"/node_modules/"]`. ### `unmockedModulePathPatterns` [array] + 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. +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/lo-dash, 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. +This is useful for some commonly used 'utility' modules that are almost always +used as implementation details almost all the time (like underscore/lo-dash, +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. +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` -Indicates whether each individual test should be reported during the run. All errors will also still be shown on the bottom after execution. +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] + Default: `[]` ##### available in Jest **21.0.0+** -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. +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/"]`. +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/"]`. diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index 252c233bd485..58b95414ec30 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -3,21 +3,26 @@ 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. +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. ## Methods ------ +--- ## 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. +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'`. +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 @@ -26,28 +31,34 @@ test('the best flavor is 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. +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. +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 theory library and you're frequently asserting that numbers are divisible by other numbers. You could abstract that into a `toBeDivisibleBy` matcher: +You can use `expect.extend` to add your own matchers to Jest. For example, let's +say that you're testing a number theory library and you're frequently asserting +that numbers are divisible by other numbers. You could abstract that into a +`toBeDivisibleBy` matcher: ```js expect.extend({ toBeDivisibleBy(received, argument) { - const pass = (received % argument == 0); + const pass = received % argument == 0; if (pass) { return { - message: () => ( - `expected ${received} not to be divisible by ${argument}` - ), + message: () => + `expected ${received} not to be divisible by ${argument}`, pass: true, }; } else { return { - message: () => (`expected ${received} to be divisible by ${argument}`), + message: () => `expected ${received} to be divisible by ${argument}`, pass: false, }; } @@ -60,23 +71,34 @@ test('even and odd numbers', () => { }); ``` -Matchers should return 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 should return 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. These helper functions 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 flip your assertion. +A boolean to let you know this matcher was called with the negated `.not` +modifier allowing you to flip your assertion. #### `this.equals(a, b)` -This is a deep-equality function that will return `true` if two objects have the same values (recursively). +This is a deep-equality function that will return `true` if two objects have the +same values (recursively). #### `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/master/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/facebook/jest/tree/master/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: +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'); @@ -85,22 +107,27 @@ expect.extend({ const pass = received === expected; const message = pass - ? () => this.utils.matcherHint('.not.toBe') + '\n\n' + - `Expected value to not be (using ===):\n` + - ` ${this.utils.printExpected(expected)}\n` + - `Received:\n` + - ` ${this.utils.printReceived(received)}` + ? () => + this.utils.matcherHint('.not.toBe') + + '\n\n' + + `Expected value to not be (using ===):\n` + + ` ${this.utils.printExpected(expected)}\n` + + `Received:\n` + + ` ${this.utils.printReceived(received)}` : () => { - const diffString = diff(expected, received, { - expand: this.expand, - }); - return this.utils.matcherHint('.toBe') + '\n\n' + - `Expected value to be (using ===):\n` + - ` ${this.utils.printExpected(expected)}\n` + - `Received:\n` + - ` ${this.utils.printReceived(received)}` + - (diffString ? `\n\nDifference:\n\n${diffString}` : ''); - }; + const diffString = diff(expected, received, { + expand: this.expand, + }); + return ( + this.utils.matcherHint('.toBe') + + '\n\n' + + `Expected value to be (using ===):\n` + + ` ${this.utils.printExpected(expected)}\n` + + `Received:\n` + + ` ${this.utils.printReceived(received)}` + + (diffString ? `\n\nDifference:\n\n${diffString}` : '') + ); + }; return {actual: received, message, pass}; }, @@ -118,11 +145,16 @@ This will print something like this: "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. +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. ### `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: +`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', () => { @@ -134,7 +166,10 @@ test('map calls its argument with a non-null argument', () => { ### `expect.any(constructor)` -`expect.any(constructor)` matches anything that was created with the given constructor. 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: +`expect.any(constructor)` matches anything that was created with the given +constructor. 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 function randocall(fn) { @@ -150,7 +185,10 @@ test('randocall calls its callback with a 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. +`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: @@ -173,21 +211,27 @@ describe('arrayContaining', () => { 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)); + 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([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. +`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: +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', () => { @@ -207,9 +251,14 @@ 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. +`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: +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', () => { @@ -221,24 +270,33 @@ test('prepareState prepares a valid state', () => { }); ``` -The `expect.hasAssertions()` call ensures that the `prepareState` callback actually gets called. +The `expect.hasAssertions()` call ensures that the `prepareState` callback +actually gets called. ### `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 **not** in the expected 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 **not** in the expected object. -Instead of literal property values in the expected object, you can use matchers, `expect.anything()`, and so on. +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: +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).toBeCalledWith(expect.objectContaining({ - x: expect.any(Number), - y: expect.any(Number), - })); + expect(onPress).toBeCalledWith( + expect.objectContaining({ + x: expect.any(Number), + y: expect.any(Number), + }), + ); }); ``` @@ -246,11 +304,13 @@ test('onPress gets called with the right thing', () => { ##### available in Jest **19.0.0+** -`expect.stringContaining(string)` matches any received string that contains the exact expected string. +`expect.stringContaining(string)` matches any received string that contains the +exact expected string. ### `expect.stringMatching(regexp)` -`expect.stringMatching(regexp)` matches any received string that matches the expected regexp. +`expect.stringMatching(regexp)` matches any received string that matches the +expected regexp. You can use it instead of a literal value: @@ -258,7 +318,8 @@ You can use it instead of a literal value: * 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`. +This example also shows how you can nest multiple asymmetric matchers, with +`expect.stringMatching` inside the `expect.arrayContaining`. ```js describe('stringMatching in arrayContaining', () => { @@ -267,21 +328,27 @@ describe('stringMatching in arrayContaining', () => { expect.stringMatching(/^[BR]ob/), ]; it('matches even if received contains additional elements', () => { - expect(['Alicia', 'Roberto', 'Evelina']) - .toEqual(expect.arrayContaining(expected)); + 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(['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. +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. +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'; @@ -290,16 +357,20 @@ expect.addSnapshotSerializer(serializer); // affects expect(value).toMatchSnapshot() assertions in the test file ``` -If you add a snapshot serializer in individual test files instead of to adding it to `snapshotSerializers` configuration: +If you add a snapshot serializer in individual test files instead of to 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). +* 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-array-string) for more information. +See [configuring Jest](Configuration.md#snapshotserializers-array-string) 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: +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', () => { @@ -311,9 +382,11 @@ test('the best flavor is not coconut', () => { ##### available in Jest **20.0.0+** -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. +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'`: +For example, this code tests that the promise resolves and that the resulting +value is `'lemon'`: ```js test('resolves to lemon', () => { @@ -335,7 +408,8 @@ test('resolves to lemon', async () => { ##### available in Jest **20.0.0+** -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. +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'`: @@ -378,7 +452,9 @@ describe('the can', () => { }); ``` -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. +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. ### `.toHaveBeenCalled()` @@ -386,7 +462,11 @@ Also under the alias: `.toBeCalled()` Use `.toHaveBeenCalled` to ensure that a mock function got called. -For example, let's say you have a `drinkAll(drink, flavor)` 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'` flavor is really weird and why would anything be octopus-flavored? You can do that with this test suite: +For example, let's say you have a `drinkAll(drink, flavor)` 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'` flavor is really weird and why would anything be octopus-flavored? +You can do that with this test suite: ```js describe('drinkAll', () => { @@ -406,9 +486,13 @@ describe('drinkAll', () => { ### `.toHaveBeenCalledTimes(number)` -Use `.toHaveBeenCalledTimes` to ensure that a mock function got called exact number of times. +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: +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', () => { @@ -422,9 +506,12 @@ test('drinkEach drinks each drink', () => { Also under the alias: `.toBeCalledWith()` -Use `.toHaveBeenCalledWith` to ensure that a mock function was called with specific arguments. +Use `.toHaveBeenCalledWith` to ensure that a mock function was called with +specific arguments. -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: +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', () => { @@ -440,7 +527,11 @@ test('registration applies correctly to orange La Croix', () => { 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: +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', () => { @@ -452,7 +543,8 @@ test('applying to all flavors does mango last', () => { ### `.toBeCloseTo(number, numDigits)` -Using exact equality with floating point numbers is a bad idea. Rounding means that intuitive things fail. For example, this test fails: +Using exact equality with floating point numbers is a bad idea. Rounding means +that intuitive things fail. For example, this test fails: ```js test('adding works sanely with simple decimals', () => { @@ -460,9 +552,12 @@ test('adding works sanely with simple decimals', () => { }); ``` -It fails because in JavaScript, `0.2 + 0.1` is actually `0.30000000000000004`. Sorry. +It fails because in JavaScript, `0.2 + 0.1` is actually `0.30000000000000004`. +Sorry. -Instead, use `.toBeCloseTo`. Use `numDigits` to control how many digits after the decimal point to check. For example, if you want to be sure that `0.2 + 0.1` is equal to `0.3` with a precision of 5 decimal digits, you can use this test: +Instead, use `.toBeCloseTo`. Use `numDigits` to control how many digits after +the decimal point to check. For example, if you want to be sure that `0.2 + 0.1` +is equal to `0.3` with a precision of 5 decimal digits, you can use this test: ```js test('adding works sanely with simple decimals', () => { @@ -470,11 +565,14 @@ test('adding works sanely with simple decimals', () => { }); ``` -The default for `numDigits` is 2, which has proved to be a good default in most cases. +The default for `numDigits` is 2, which has proved to be a good default in most +cases. ### `.toBeDefined()` -Use `.toBeDefined` to check that a variable is not undefined. For example, if you just want to check that a function `fetchNewFlavorIdea()` returns *something*, you can write: +Use `.toBeDefined` to check that a variable is not undefined. For example, if +you just want to check that a function `fetchNewFlavorIdea()` returns +_something_, you can write: ```js test('there is a new flavor idea', () => { @@ -482,11 +580,14 @@ test('there is a new flavor idea', () => { }); ``` -You could write `expect(fetchNewFlavorIdea()).not.toBe(undefined)`, but it's better practice to avoid referring to `undefined` directly in your code. +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, you just want to ensure a value is false in a boolean context. For example, let's say you have some application code that looks like: +Use `.toBeFalsy` when you don't care what a value is, you just 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(); @@ -495,7 +596,9 @@ if (!getErrors()) { } ``` -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: +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', () => { @@ -504,11 +607,14 @@ test('drinking La Croix does not lead to errors', () => { }); ``` -In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. +In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, +`undefined`, and `NaN`. Everything else is truthy. ### `.toBeGreaterThan(number)` -To compare floating point numbers, you can use `toBeGreaterThan`. For example, if you want to test that `ouncesPerCan()` returns a value of more than 10 ounces, write: +To compare floating point numbers, you can use `toBeGreaterThan`. For example, +if you want to test that `ouncesPerCan()` returns a value of more than 10 +ounces, write: ```js test('ounces per can is more than 10', () => { @@ -518,7 +624,9 @@ test('ounces per can is more than 10', () => { ### `.toBeGreaterThanOrEqual(number)` -To compare floating point numbers, you can use `toBeGreaterThanOrEqual`. For example, if you want to test that `ouncesPerCan()` returns a value of at least 12 ounces, write: +To compare floating point numbers, you can use `toBeGreaterThanOrEqual`. For +example, if you want to test that `ouncesPerCan()` returns a value of at least +12 ounces, write: ```js test('ounces per can is at least 12', () => { @@ -528,7 +636,9 @@ test('ounces per can is at least 12', () => { ### `.toBeLessThan(number)` -To compare floating point numbers, you can use `toBeLessThan`. For example, if you want to test that `ouncesPerCan()` returns a value of less than 20 ounces, write: +To compare floating point numbers, you can use `toBeLessThan`. For example, if +you want to test that `ouncesPerCan()` returns a value of less than 20 ounces, +write: ```js test('ounces per can is less than 20', () => { @@ -538,7 +648,9 @@ test('ounces per can is less than 20', () => { ### `.toBeLessThanOrEqual(number)` -To compare floating point numbers, you can use `toBeLessThanOrEqual`. For example, if you want to test that `ouncesPerCan()` returns a value of at most 12 ounces, write: +To compare floating point numbers, you can use `toBeLessThanOrEqual`. For +example, if you want to test that `ouncesPerCan()` returns a value of at most 12 +ounces, write: ```js test('ounces per can is at most 12', () => { @@ -548,7 +660,8 @@ test('ounces per can is at most 12', () => { ### `.toBeInstanceOf(Class)` -Use `.toBeInstanceOf(Class)` to check that an object is an instance of a class. This matcher uses `instanceof` underneath. +Use `.toBeInstanceOf(Class)` to check that an object is an instance of a class. +This matcher uses `instanceof` underneath. ```js class A {} @@ -560,7 +673,8 @@ 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. +`.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() { @@ -574,7 +688,9 @@ test('bloop returns null', () => { ### `.toBeTruthy()` -Use `.toBeTruthy` when you don't care what a value is, you just want to ensure a value is true in a boolean context. For example, let's say you have some application code that looks like: +Use `.toBeTruthy` when you don't care what a value is, you just 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(); @@ -583,7 +699,10 @@ if (thirstInfo()) { } ``` -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 just want to test that `thirstInfo` will be truthy after drinking some La Croix, you could write: +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 just 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', () => { @@ -592,11 +711,14 @@ test('drinking La Croix leads to having thirst info', () => { }); ``` -In JavaScript, there are six falsy values: `false`, `0`, `''`, `null`, `undefined`, and `NaN`. Everything else is truthy. +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: +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', () => { @@ -604,13 +726,17 @@ test('the best drink for octopus flavor is undefined', () => { }); ``` -You could write `expect(bestDrinkForFlavor('octopus')).toBe(undefined)`, but it's better practice to avoid referring to `undefined` directly in your code. +You could write `expect(bestDrinkForFlavor('octopus')).toBe(undefined)`, but +it's better practice to avoid referring to `undefined` directly in your code. ### `.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. +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: +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', () => { @@ -620,8 +746,10 @@ test('the flavor list contains lime', () => { ### `.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. +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', () => { @@ -634,7 +762,10 @@ describe('my beverage', () => { ### `.toEqual(value)` -Use `.toEqual` when you want to check that two objects have the same value. This matcher recursively checks the equality of all fields, rather than checking for object identity—this is also known as "deep equal". For example, `toEqual` and `toBe` behave differently in this test suite, so all the tests pass: +Use `.toEqual` when you want to check that two objects have the same value. This +matcher recursively checks the equality of all fields, rather than checking for +object identity—this is also known as "deep equal". For example, `toEqual` and +`toBe` behave differently in this test suite, so all the tests pass: ```js const can1 = { @@ -656,11 +787,14 @@ describe('the La Croix cans on my desk', () => { }); ``` -> Note: `.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. +> Note: `.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. ### `.toHaveLength(number)` -Use `.toHaveLength` to check that an object has a `.length` property and it is set to a certain numeric value. +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. @@ -674,7 +808,9 @@ expect('').not.toHaveLength(5); 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: +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', () => { @@ -697,9 +833,16 @@ describe('grapefruits are healthy', () => { ### `.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. +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 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. @@ -729,32 +872,18 @@ test('the house has my desired features', () => { ```js describe('toMatchObject applied to arrays arrays', () => { test('the number of elements must match exactly', () => { - expect([ - { foo: 'bar' }, - { baz: 1 } - ]).toMatchObject([ - { foo: 'bar' }, - { baz: 1 } - ]); + expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}, {baz: 1}]); }); // .arrayContaining "matches a received array which contains elements that are *not* in the expected array" test('.toMatchObject does not allow extra elements', () => { - expect([ - { foo: 'bar' }, - { baz: 1 } - ]).toMatchObject([ - { foo: 'bar' } - ]); + expect([{foo: 'bar'}, {baz: 1}]).toMatchObject([{foo: 'bar'}]); }); 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 } + expect([{foo: 'bar'}, {baz: 1, extra: 'quux'}]).toMatchObject([ + {foo: 'bar'}, + {baz: 1}, ]); }); }); @@ -762,13 +891,18 @@ describe('toMatchObject applied to arrays arrays', () => { ### `.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 use [dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) for deep references. +Use `.toHaveProperty` to check if property at provided reference `keyPath` +exists for an object. For checking deeply nested properties in an object use +[dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) +for deep references. -Optionally, you can provide a `value` to check if it's equal to the value present at `keyPath` on the target object. This matcher uses 'deep equality' (like `toEqual()`) and recursively checks the equality of all fields. +Optionally, you can provide a `value` to check if it's equal to the value +present at `keyPath` on the target object. This matcher uses 'deep equality' +(like `toEqual()`) and recursively checks the equality of all fields. -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. +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 @@ -803,17 +937,22 @@ test('this house has my desired features', () => { ### `.toMatchSnapshot(optionalString)` -This ensures that a value matches the most recent snapshot. Check out [the Snapshot Testing guide](SnapshotTesting.md) for more information. +This ensures that a value matches the most recent snapshot. Check out +[the Snapshot Testing guide](SnapshotTesting.md) for more information. -You can also specify an optional snapshot name. Otherwise, the name is inferred from the test. +You can also specify an optional snapshot name. Otherwise, the name is inferred +from the test. -*Note: While snapshot testing is most commonly used with React components, any serializable value can be used as a snapshot.* +_Note: While snapshot testing is most commonly used with React components, any +serializable value can be used as a snapshot._ ### `.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: +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', () => { @@ -823,7 +962,10 @@ test('throws on octopus', () => { }); ``` -If you want to test that a specific error gets thrown, you can provide an argument to `toThrow`. The argument can be a string for the error message, a class for the error, or a regex that should match the error. For example, let's say that `drinkFlavor` is coded like this: +If you want to test that a specific error gets thrown, you can provide an +argument to `toThrow`. The argument can be a string for the error message, a +class for the error, or a regex that should match the error. For example, let's +say that `drinkFlavor` is coded like this: ```js function drinkFlavor(flavor) { @@ -853,11 +995,15 @@ test('throws on octopus', () => { }); ``` -> Note: You must wrap the code in a function, otherwise the error will not be caught and the assertion will fail. +> Note: You must wrap the code in a function, otherwise the error will not be +> caught and the assertion will fail. ### `.toThrowErrorMatchingSnapshot()` -Use `.toThrowErrorMatchingSnapshot` to test that a function throws an error matching the most recent snapshot when it is called. For example, let's say you have a `drinkFlavor` function that throws whenever the flavor is `'octopus'`, and is coded like this: +Use `.toThrowErrorMatchingSnapshot` to test that a function throws an error +matching the most recent snapshot when it is called. 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) { @@ -886,4 +1032,6 @@ And it will generate the following snapshot: exports[`drinking flavors throws on octopus 1`] = `"yuck, octopus flavor"`; ``` -Check out [React Tree Snapshot Testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html) for more information on snapshot testing. +Check out +[React Tree Snapshot Testing](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html) +for more information on snapshot testing. diff --git a/docs/GettingStarted.md b/docs/GettingStarted.md index 340bf01fbe4c..4991001c5db4 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -15,7 +15,8 @@ Or via [`yarn`](https://yarnpkg.com/en/package/jest): yarn add --dev jest ``` -Let's get started by writing a test for a hypothetical function that adds two numbers. First, create a `sum.js` file: +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) { @@ -53,33 +54,44 @@ PASS ./sum.test.js **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). +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 `npm install -g jest`) with variety of useful options. +You can run Jest directly from the CLI (if it's globally available in your +`PATH`, e.g. by `npm install -g jest`) with 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: +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. +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 ### Using Babel -To use [Babel](http://babeljs.io/), install the `babel-jest` and `regenerator-runtime` packages: +To use [Babel](http://babeljs.io/), install the `babel-jest` and +`regenerator-runtime` packages: ``` npm install --save-dev babel-jest regenerator-runtime ``` -*Note: Explicitly installing `regenerator-runtime` is not needed if you use `npm` 3 or 4 or Yarn* +_Note: Explicitly installing `regenerator-runtime` is not needed if you use +`npm` 3 or 4 or Yarn_ -Don't forget to add a [`.babelrc`](https://babeljs.io/docs/usage/babelrc/) file in your project's root folder. For example, if you are using ES6 and [React.js](https://facebook.github.io/react/) with the [`babel-preset-es2015`](https://babeljs.io/docs/plugins/preset-es2015/) and [`babel-preset-react`](https://babeljs.io/docs/plugins/preset-react/) presets: +Don't forget to add a [`.babelrc`](https://babeljs.io/docs/usage/babelrc/) file +in your project's root folder. For example, if you are using ES6 and +[React.js](https://facebook.github.io/react/) with the +[`babel-preset-es2015`](https://babeljs.io/docs/plugins/preset-es2015/) and +[`babel-preset-react`](https://babeljs.io/docs/plugins/preset-react/) presets: ```json { @@ -89,14 +101,18 @@ Don't forget to add a [`.babelrc`](https://babeljs.io/docs/usage/babelrc/) file You are now set up to use all ES6 features and React specific syntax. -> Note: If you are using a more complicated Babel configuration, using Babel's `env` option, -keep in mind that Jest will automatically define `NODE_ENV` as `test`. -It will not use `development` section like Babel does by default when no `NODE_ENV` is set. +> Note: If you are using a more complicated Babel configuration, using Babel's +> `env` option, keep in mind that Jest will automatically define `NODE_ENV` as +> `test`. It will not use `development` section like Babel does by default when +> no `NODE_ENV` is set. + +> Note: If you've turned off transpilation of ES2015 modules with the option `{ +> "modules": false }`, you have to make sure to turn this on in your test +> environment. -> Note: If you've turned off transpilation of ES2015 modules with the option `{ "modules": false }`, you have to make sure to turn this on in your test environment. ```json { - "presets": [["es2015", { "modules": false }], "react"], + "presets": [["es2015", {"modules": false}], "react"], "env": { "test": { "presets": [["es2015"], "react"] @@ -105,7 +121,10 @@ It will not use `development` section like Babel does by default when no `NODE_E } ``` -> 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: +> 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: ```json // package.json @@ -118,8 +137,12 @@ It will not use `development` section like Babel does by default when no `NODE_E ### Using webpack -Jest can be used in projects that use [webpack](https://webpack.github.io/) 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. +Jest can be used in projects that use [webpack](https://webpack.github.io/) 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 TypeScript -To use TypeScript in your tests you can use [ts-jest](https://github.com/kulshekhar/ts-jest). +To use TypeScript in your tests you can use +[ts-jest](https://github.com/kulshekhar/ts-jest). diff --git a/docs/GlobalAPI.md b/docs/GlobalAPI.md index 19a69c8d673f..7117d8e5a4c9 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -3,21 +3,24 @@ 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. +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. ## Methods ------ +--- ## Reference ### `afterAll(fn)` -Runs a function after all the tests in this file have completed. If the function returns a promise, Jest waits for that promise to resolve before continuing. +Runs a function after all the tests in this file have completed. If the function +returns a promise, Jest waits for that promise to resolve before continuing. -This is often useful if you want to clean up some global setup state that is shared across tests. +This is often useful if you want to clean up some global setup state that is +shared across tests. For example: @@ -45,17 +48,23 @@ test('can insert a thing', () => { }); ``` -Here the `afterAll` ensures that `cleanUpDatabase` is called after all tests run. +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 `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. +If you want to run some cleanup after every test instead of after all tests, use +`afterEach` instead. ### `afterEach(fn)` -Runs a function after each one of the tests in this file completes. If the function returns a promise, Jest waits for that promise to resolve before continuing. +Runs a function after each one of the tests in this file completes. If the +function returns a promise, Jest waits for that promise to resolve before +continuing. -This is often useful if you want to clean up some temporary state that is created by each test. +This is often useful if you want to clean up some temporary state that is +created by each test. For example: @@ -83,17 +92,22 @@ test('can insert a thing', () => { }); ``` -Here the `afterEach` ensures that `cleanUpDatabase` is called after each test runs. +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 `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. +If you want to run some cleanup just once, after all of the tests run, use +`afterAll` instead. ### `beforeAll(fn)` -Runs a function before any of the tests in this file run. If the function returns a promise, Jest waits for that promise to resolve before running tests. +Runs a function before any of the tests in this file run. If the function +returns a promise, Jest waits for that promise to resolve before running tests. -This is often useful if you want to set up some global state that will be used by many tests. +This is often useful if you want to set up some global state that will be used +by many tests. For example: @@ -117,17 +131,25 @@ test('can find things', () => { }); ``` -Here the `beforeAll` ensures that the database is set up before tests run. If setup was synchronous, you could just do this without `beforeAll`. The key is that Jest will wait for a promise to resolve, so you can have asynchronous setup as well. +Here the `beforeAll` ensures that the database is set up before tests run. If +setup was synchronous, you could just 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 `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. +If you want to run something before every test instead of before any test runs, +use `beforeEach` instead. ### `beforeEach(fn)` -Runs a function before each of the tests in this file runs. If the function returns a promise, Jest waits for that promise to resolve before running the test. +Runs a function before each of the tests in this file runs. If the function +returns a promise, Jest waits for that promise to resolve before running the +test. -This is often useful if you want to reset some global state that will be used by many tests. +This is often useful if you want to reset some global state that will be used by +many tests. For example: @@ -157,13 +179,17 @@ test('can insert a thing', () => { 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 `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. +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 in one "test suite". For example, if you have a `myBeverage` object that is supposed to be delicious but not sour, you could test it with: +`describe(name, fn)` creates a block that groups together several related tests +in one "test suite". 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 = { @@ -182,7 +208,9 @@ describe('my beverage', () => { }); ``` -This isn't required - you can just write the `test` blocks directly at the top level. But this can be handy if you prefer your tests to be organized into groups. +This isn't required - you can just 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: @@ -240,7 +268,8 @@ describe('my other beverage', () => { Also under the alias: `xdescribe(name, fn)` -You can use `describe.skip` if you do not want to run a particular describe block: +You can use `describe.skip` if you do not want to run a particular describe +block: ```js describe('my beverage', () => { @@ -258,7 +287,8 @@ describe.skip('my other beverage', () => { }); ``` -Using `describe.skip` is often just an easier alternative to temporarily commenting out a chunk of tests. +Using `describe.skip` is often just an easier alternative to temporarily +commenting out a chunk of tests. ### `require.requireActual(moduleName)` @@ -274,7 +304,9 @@ whether the module should be required normally or not. Also under the alias: `it(name, fn)` -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: +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', () => { @@ -282,12 +314,17 @@ test('did not rain', () => { }); ``` -The first argument is the test name; the second argument is a function that contains the expectations to test. +The first argument is the test name; the second argument is a function that +contains the expectations to test. -> Note: If a **promise is returned** from `test`, Jest will wait for the promise to resolve before letting the test complete. -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. See how to test async code [here](TestingAsyncCode.md#callbacks). +> Note: If a **promise is returned** from `test`, Jest will wait for the promise +> to resolve before letting the test complete. 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. See how to test async code +> [here](TestingAsyncCode.md#callbacks). -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: +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', () => { @@ -297,13 +334,16 @@ test('has lemon in it', () => { }); ``` -Even though the call to `test` will return right away, the test doesn't complete until the promise resolves as well. +Even though the call to `test` will return right away, the test doesn't complete +until the promise resolves as well. ### `test.only(name, fn)` Also under the aliases: `it.only(name, fn)` or `fit(name, fn)` -When you are debugging a large codebase, 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. +When you are debugging a large codebase, 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. For example, let's say you had these tests: @@ -319,13 +359,19 @@ test('it is not snowing', () => { Only the "it is raining" test will run, since it is run with `test.only`. -Usually you wouldn't check code using `test.only` into source control - you would use it just for debugging, and remove it once you have fixed the broken tests. +Usually you wouldn't check code using `test.only` into source control - you +would use it just for debugging, and remove it once you have fixed the broken +tests. ### `test.skip(name, fn)` -Also under the aliases: `it.skip(name, fn)` or `xit(name, fn)` or `xtest(name, fn)` +Also under the aliases: `it.skip(name, fn)` or `xit(name, fn)` or `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 just delete this code, you can use `test.skip` to specify some tests to skip. +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 just delete this code, you can use `test.skip` to specify some +tests to skip. For example, let's say you had these tests: @@ -339,6 +385,8 @@ test.skip('it is not snowing', () => { }); ``` -Only the "it is raining" test will run, since the other test is run with `test.skip`. +Only the "it is raining" test will run, since the other test is run with +`test.skip`. -You could simply comment the test out, but it's often a bit nicer to use `test.skip` because it will maintain indentation and syntax highlighting. +You could simply comment the test out, but it's often a bit nicer to use +`test.skip` because it will maintain indentation and syntax highlighting. diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 9bc2cbf49f4f..5c8291672b68 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -3,86 +3,112 @@ 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. +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. ## Methods - - [`jest.clearAllTimers()`](#jestclearalltimers) - - [`jest.disableAutomock()`](#jestdisableautomock) - - [`jest.enableAutomock()`](#jestenableautomock) - - [`jest.fn(implementation)`](#jestfnimplementation) - - [`jest.isMockFunction(fn)`](#jestismockfunctionfn) - - [`jest.genMockFromModule(moduleName)`](#jestgenmockfrommodulemodulename) - - [`jest.mock(moduleName, factory, options)`](#jestmockmodulename-factory-options) - - [`jest.unmock(moduleName)`](#jestunmockmodulename) - - [`jest.doMock(moduleName, factory, options)`](#jestdomockmodulename-factory-options) - - [`jest.dontMock(moduleName)`](#jestdontmockmodulename) - - [`jest.clearAllMocks()`](#jestclearallmocks) - - [`jest.resetAllMocks()`](#jestresetallmocks) - - [`jest.restoreAllMocks()`](#jestrestoreallmocks) - - [`jest.resetModules()`](#jestresetmodules) - - [`jest.runAllTicks()`](#jestrunallticks) - - [`jest.runAllTimers()`](#jestrunalltimers) - - [`jest.advanceTimersByTime(msToRun)`](#jestadvancetimersbytimemstorun) - - [`jest.runOnlyPendingTimers()`](#jestrunonlypendingtimers) - - [`jest.setMock(moduleName, moduleExports)`](#jestsetmockmodulename-moduleexports) - - [`jest.setTimeout(timeout)`](#jestsettimeouttimeout) - - [`jest.useFakeTimers()`](#jestusefaketimers) - - [`jest.useRealTimers()`](#jestuserealtimers) - - [`jest.spyOn(object, methodName)`](#jestspyonobject-methodname) - ------ +* [`jest.clearAllTimers()`](#jestclearalltimers) +* [`jest.disableAutomock()`](#jestdisableautomock) +* [`jest.enableAutomock()`](#jestenableautomock) +* [`jest.fn(implementation)`](#jestfnimplementation) +* [`jest.isMockFunction(fn)`](#jestismockfunctionfn) +* [`jest.genMockFromModule(moduleName)`](#jestgenmockfrommodulemodulename) +* [`jest.mock(moduleName, factory, options)`](#jestmockmodulename-factory-options) +* [`jest.unmock(moduleName)`](#jestunmockmodulename) +* [`jest.doMock(moduleName, factory, options)`](#jestdomockmodulename-factory-options) +* [`jest.dontMock(moduleName)`](#jestdontmockmodulename) +* [`jest.clearAllMocks()`](#jestclearallmocks) +* [`jest.resetAllMocks()`](#jestresetallmocks) +* [`jest.restoreAllMocks()`](#jestrestoreallmocks) +* [`jest.resetModules()`](#jestresetmodules) +* [`jest.runAllTicks()`](#jestrunallticks) +* [`jest.runAllTimers()`](#jestrunalltimers) +* [`jest.advanceTimersByTime(msToRun)`](#jestadvancetimersbytimemstorun) +* [`jest.runOnlyPendingTimers()`](#jestrunonlypendingtimers) +* [`jest.setMock(moduleName, moduleExports)`](#jestsetmockmodulename-moduleexports) +* [`jest.setTimeout(timeout)`](#jestsettimeouttimeout) +* [`jest.useFakeTimers()`](#jestusefaketimers) +* [`jest.useRealTimers()`](#jestuserealtimers) +* [`jest.spyOn(object, methodName)`](#jestspyonobject-methodname) + +--- ## Reference ### `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. +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.disableAutomock()` + Disables automatic mocking in the module loader. -After this method is called, all `require()`s will return the real versions of each module (rather than a mocked version). +After this method is called, all `require()`s will return the real versions of +each module (rather than a mocked version). -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. +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/lo-dash, array utilities etc) and entire libraries like React.js. +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/lo-dash, array utilities etc) and entire +libraries like React.js. Returns the `jest` object for chaining. -*Note: this method was previously called `autoMockOff`. 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.* +_Note: this method was previously called `autoMockOff`. 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. Returns the `jest` object for chaining. -*Note: this method was previously called `autoMockOn`. 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.* +_Note: this method was previously called `autoMockOn`. 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.fn(implementation)` -Returns a new, unused [mock function](MockFunctionAPI.md). Optionally takes a mock implementation. + +Returns a new, unused [mock function](MockFunctionAPI.md). Optionally takes a +mock implementation. ```js - const mockFn = jest.fn(); - mockFn(); - expect(mockFn).toHaveBeenCalled(); +const mockFn = jest.fn(); +mockFn(); +expect(mockFn).toHaveBeenCalled(); - // With a mock implementation: - const returnsTrue = jest.fn(() => true); - console.log(returnsTrue()); // true; +// 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.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. +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. ### `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: + +Mocks a module with an auto-mocked version when it is being required. `factory` +and `options` are optional. For example: ```js // banana.js @@ -96,7 +122,8 @@ 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: +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', () => { @@ -107,34 +134,51 @@ const moduleName = require('../moduleName'); // This runs the function specified moduleName(); // Will return '42'; ``` -The third argument can be used to create virtual mocks – mocks of modules that don't exist anywhere in the system: +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', () => { - /* +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}); + }, + {virtual: true}, +); ``` -*Warning: Importing a module in a setup file (as specified by `setupTestFrameworkScriptFile`) will prevent mocking for the module in question, as well as all the modules that it imports.* +_Warning: Importing a module in a setup file (as specified by +`setupTestFrameworkScriptFile`) 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 run after the test file that mocks the module. +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 run 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). +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.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: +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(() => { @@ -161,28 +205,43 @@ test('moduleName 2', () => { 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. + +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.clearAllMocks()` -Clears the `mock.calls` and `mock.instances` properties of all mocks. Equivalent to calling `.mockClear()` on every mocked function. + +Clears the `mock.calls` and `mock.instances` properties of all mocks. Equivalent +to calling `.mockClear()` on every mocked function. Returns the `jest` object for chaining. ### `jest.resetAllMocks()` -Resets the state of all mocks. Equivalent to calling `.mockReset()` on every mocked function. + +Resets the state of all mocks. Equivalent to calling `.mockReset()` on every +mocked function. Returns the `jest` object for chaining. ### `jest.restoreAllMocks()` + ##### available in Jest **21.1.0+** -Restores all mocks back to their original value. Equivalent to calling `.mockRestore` on every mocked function. Beware that `jest.restoreAllMocks()` only works when mock was created with `jest.spyOn`; other mocks will require you to manually restore them. + +Restores all mocks back to their original value. Equivalent to calling +`.mockRestore` on every mocked function. Beware that `jest.restoreAllMocks()` +only works when mock was created with `jest.spyOn`; other mocks will require you +to manually restore them. ### `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. + +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(); @@ -192,6 +251,7 @@ sum1 === sum2; ``` Example in a test: + ```js beforeEach(() => { jest.resetModules(); @@ -210,49 +270,91 @@ test('works too', () => { 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. +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 the **macro**-task queue (i.e., all tasks queued by `setTimeout()`, `setInterval()`, and `setImmediate()`). -When this API is called, all pending "macro-tasks" that have been queued via `setTimeout()` or `setInterval()` will be executed. Additionally if those macro-tasks themselves schedule new macro-tasks, those will be continually exhausted until there are no more macro-tasks remaining in the queue. +Exhausts the **macro**-task queue (i.e., all tasks queued by `setTimeout()`, +`setInterval()`, and `setImmediate()`). + +When this API is called, all pending "macro-tasks" that have been queued via +`setTimeout()` or `setInterval()` will be executed. Additionally if those +macro-tasks themselves schedule new macro-tasks, those will be continually +exhausted until there are no more macro-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. +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)` + ##### renamed in Jest **21.3.0+** + Also under the alias: `.runTimersToTime()` -Executes only the macro task queue (i.e. all tasks queued by `setTimeout()` or `setInterval()` and `setImmediate()`). +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 timeframe 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. +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 timeframe 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. +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.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. +Explicitly supplies the mock object that the module system should return for the +specified module. -In these rare scenarios you can use this API to manually fill the slot in the module system's mock-module registry. +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. -*Note 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.* +_Note 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.setTimeout(timeout)` -Set the default timeout interval for tests and before/after hooks in milliseconds. +Set the default timeout interval for tests and before/after hooks in +milliseconds. -*Note: The default timeout interval is 5 seconds if this method is not called.* +_Note: The default timeout interval is 5 seconds if this method is not called._ Example: @@ -261,20 +363,31 @@ jest.setTimeout(1000); // 1 second ``` ### `jest.useFakeTimers()` -Instructs Jest to use fake versions of the standard timer functions (`setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`, `nextTick`, `setImmediate` and `clearImmediate`). + +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.spyOn(object, methodName)` + ##### available in Jest **19.0.0+** -Creates a mock function similar to `jest.fn` but also tracks calls to `object[methodName]`. Returns a Jest mock function. -*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);`* +Creates a mock function similar to `jest.fn` but also tracks calls to +`object[methodName]`. Returns a Jest mock function. + +_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);`_ Example: @@ -289,6 +402,7 @@ module.exports = video; ``` Example test: + ```js const video = require('./video'); diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index 9b923f97844f..2f3f2b150d66 100644 --- a/docs/ManualMocks.md +++ b/docs/ManualMocks.md @@ -3,9 +3,20 @@ 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. - -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. Note that the `__mocks__` folder is case-sensitive, so naming the directory `__MOCKS__` will break on some systems. If the module you are mocking is a node module (eg: `fs`), the mock should be placed in the `__mocks__` directory adjacent to `node_modules` (unless you configured [`roots`](Configuration.md#roots-array-string) to point to a folder other than the project root). Eg: +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. + +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. Note that the `__mocks__` folder is +case-sensitive, so naming the directory `__MOCKS__` will break on some systems. +If the module you are mocking is a node module (eg: `fs`), the mock should be +placed in the `__mocks__` directory adjacent to `node_modules` (unless you +configured [`roots`](Configuration.md#roots-array-string) to point to a folder +other than the project root). Eg: ```bash . @@ -20,10 +31,15 @@ Manual mocks are defined by writing a module in a `__mocks__/` subdirectory imme └── 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, manual mocks will take precedence over node modules 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. +When a manual mock exists for a given module, Jest's module system will use that +module when explicitly calling `jest.mock('moduleName')`. However, manual mocks +will take precedence over node modules 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. -Here's a contrived example where we have a module that provides a summary of -all the files in a given directory. +Here's a contrived example where we have a module that provides a summary of all +the files in a given directory. ```javascript // FileSummarizer.js @@ -41,8 +57,8 @@ function summarizeFilesInDirectorySync(directory) { 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 +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: @@ -104,7 +120,7 @@ describe('listFilesInDirectorySync', () => { test('includes all files in the directory in the summary', () => { const FileSummarizer = require('../FileSummarizer'); const fileSummary = FileSummarizer.summarizeFilesInDirectorySync( - '/path/to' + '/path/to', ); expect(fileSummary.length).toBe(2); @@ -112,23 +128,27 @@ describe('listFilesInDirectorySync', () => { }); ``` -The example mock shown here uses [`jest.genMockFromModule`](JestObjectAPI.md#jestgenmockfrommodulemodulename) -to generate an automatic mock, and overrides its default behavior. This is the +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 simply 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. +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 `require.requireActual(moduleName)` in your manual mock and amending it with mock functions before exporting it. +To ensure that a manual mock and its real implementation stay in sync, it might +be useful to require the real module using `require.requireActual(moduleName)` +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/master/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) +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 diff --git a/docs/MigrationGuide.md b/docs/MigrationGuide.md index 0dc9b1118ac2..cde96d2504fd 100644 --- a/docs/MigrationGuide.md +++ b/docs/MigrationGuide.md @@ -3,24 +3,32 @@ 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 and easy 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). +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 and easy 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), +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/tj/should.js/) -or [Tape](https://github.com/substack/tape) -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). +[Should.js](https://github.com/tj/should.js/) or +[Tape](https://github.com/substack/tape) 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). Install Jest Codemods with `npm` by running: @@ -28,10 +36,12 @@ Install Jest Codemods with `npm` by running: npm install -g jest-codemods ``` -To transform your existing tests, navigate to the project containing the tests and run: +To transform your existing tests, navigate to the project containing the tests +and run: ``` jest-codemods ``` -More information can be found at [https://github.com/skovhus/jest-codemods](https://github.com/skovhus/jest-codemods). +More information can be found at +[https://github.com/skovhus/jest-codemods](https://github.com/skovhus/jest-codemods). diff --git a/docs/MockFunctionAPI.md b/docs/MockFunctionAPI.md index 20adecee8b1b..daf69581382d 100644 --- a/docs/MockFunctionAPI.md +++ b/docs/MockFunctionAPI.md @@ -3,37 +3,46 @@ 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 just 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. +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 +just 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 ------ +--- ## Reference ### `mockFn.getMockName()` + ##### available in Jest **21.3.0+** Returns the mock name string set by calling `mockFn.mockName(value)`. ### `mockFn.mock.calls` -An array that represents all calls that have been made into this mock function. Each call is represented by 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: +An array that represents all calls that have been made into this mock function. +Each call is represented by 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'], -]; +[['arg1', 'arg2'], ['arg3', 'arg4']]; ``` ### `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: +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(); @@ -46,32 +55,56 @@ mockFn.mock.instances[1] === b; // true ``` ### `mockFn.mockClear()` -Resets all information stored in the [`mockFn.mock.calls`](#mockfn-mock-calls) and [`mockFn.mock.instances`](#mockfn-mock-instances) arrays. -Often this is useful when you want to clean up a mock's usage data between two assertions. +Resets all information stored in the [`mockFn.mock.calls`](#mockfn-mock-calls) +and [`mockFn.mock.instances`](#mockfn-mock-instances) arrays. + +Often this is useful when you want to clean up a mock's usage data between two +assertions. -Beware that `mockClear` will replace `mockFn.mock`, not just [`mockFn.mock.calls`](#mockfn-mock-calls) and [`mockFn.mock.instances`](#mockfn-mock-instances). You should therefore avoid assigning `mockFn.mock` to other variables, temporary or not, to make sure you don't access stale data. +Beware that `mockClear` will replace `mockFn.mock`, not just +[`mockFn.mock.calls`](#mockfn-mock-calls) and +[`mockFn.mock.instances`](#mockfn-mock-instances). You should therefore avoid +assigning `mockFn.mock` to other variables, temporary or not, to make sure you +don't access stale data. -The [`clearMocks`](configuration.html#clearmocks-boolean) configuration option is available to clear mocks automatically between tests. +The [`clearMocks`](configuration.html#clearmocks-boolean) configuration option +is available to clear mocks automatically between tests. ### `mockFn.mockReset()` -Resets all information stored in the mock, including any initial implementation and mock name given. -This is useful when you want to completely restore a mock back to its initial state. +Resets all information stored in the mock, including any initial implementation +and mock name given. -Beware that `mockReset` will replace `mockFn.mock`, not just [`mockFn.mock.calls`](#mockfn-mock-calls) and [`mockFn.mock.instances`](#mockfn-mock-instances). You should therefore avoid assigning `mockFn.mock` to other variables, temporary or not, to make sure you don't access stale data. +This is useful when you want to completely restore a mock back to its initial +state. + +Beware that `mockReset` will replace `mockFn.mock`, not just +[`mockFn.mock.calls`](#mockfn-mock-calls) and +[`mockFn.mock.instances`](#mockfn-mock-instances). You should therefore avoid +assigning `mockFn.mock` to other variables, temporary or not, to make sure you +don't access stale data. ### `mockFn.mockRestore()` + Removes the mock and restores the initial implementation. -This is useful when you want to mock functions in certain test cases and restore the original implementation in others. +This is useful when you want to mock functions in certain test cases and restore +the original implementation in others. -Beware that `mockFn.mockRestore` only works when mock was created with `jest.spyOn`. Thus you have to take care of restoration yourself when manually assigning `jest.fn()`. +Beware that `mockFn.mockRestore` only works when 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. -*Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`.* +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. + +_Note: `jest.fn(implementation)` is a shorthand for +`jest.fn().mockImplementation(implementation)`._ For example: @@ -113,7 +146,10 @@ 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. + +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. ``` var myMockFn = jest.fn() @@ -127,7 +163,10 @@ 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: +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: ``` var myMockFn = jest.fn(() => 'default') @@ -139,8 +178,11 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); ``` ### `mockFn.mockName(value)` + ##### available in Jest **21.3.0+** -Accepts a string to use in test result output in place of "jest.fn()" to indicate which mock function is being referenced. + +Accepts a string to use in test result output in place of "jest.fn()" to +indicate which mock function is being referenced. For example: @@ -151,14 +193,15 @@ expect(mockFn).toHaveBeenCalled(); ``` Will result in this error: + ``` expect(mockedFunction).toHaveBeenCalled() - + Expected mock function to have been called. ``` - ### `mockFn.mockReturnThis()` + Just a simple sugar function for: ```js @@ -168,6 +211,7 @@ jest.fn(function() { ``` ### `mockFn.mockReturnValue(value)` + Accepts a value that will be returned whenever the mock function is called. ```js @@ -179,7 +223,11 @@ mock(); // 43 ``` ### `mockFn.mockReturnValueOnce(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`. + +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`. ``` const myMockFn = jest.fn() diff --git a/docs/MockFunctions.md b/docs/MockFunctions.md index 1c16e5199ead..517badea4111 100644 --- a/docs/MockFunctions.md +++ b/docs/MockFunctions.md @@ -9,9 +9,9 @@ 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. +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 @@ -92,9 +92,10 @@ const myMock = jest.fn(); console.log(myMock()); // > undefined -myMock.mockReturnValueOnce(10) - .mockReturnValueOnce('x') - .mockReturnValue(true); +myMock + .mockReturnValueOnce(10) + .mockReturnValueOnce('x') + .mockReturnValue(true); console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true @@ -111,9 +112,7 @@ const filterTestFn = jest.fn(); // Make the mock return `true` for the first call, // and `false` for the second call -filterTestFn - .mockReturnValueOnce(true) - .mockReturnValueOnce(false); +filterTestFn.mockReturnValueOnce(true).mockReturnValueOnce(false); const result = [11, 12].filter(filterTestFn); @@ -132,8 +131,8 @@ function that's not directly being tested. 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. +can be done with `jest.fn` or the `mockImplementationOnce` method on mock +functions. ```javascript const myMockFn = jest.fn(cb => cb(null, true)); @@ -164,13 +163,13 @@ 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() +const myMockFn = jest + .fn() .mockImplementationOnce(cb => cb(null, true)) .mockImplementationOnce(cb => cb(null, false)); @@ -182,11 +181,12 @@ myMockFn((err, val) => console.log(val)); ``` 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): +`mockImplementationOnce`, it will execute the default implementation set with +`jest.fn` (if it is defined): ```javascript -const myMockFn = jest.fn(() => 'default') +const myMockFn = jest + .fn(() => 'default') .mockImplementationOnce(() => 'first call') .mockImplementationOnce(() => 'second call'); @@ -213,12 +213,17 @@ const otherObj = { ``` ## Mock Names + ##### available in Jest **21.3.0+** -You can optionally provide a name for your mock functions, which will be displayed instead of "jest.fn()" in test error output. Use this if you want to be able to quickly identify the mock function reporting an error in your test output. +You can optionally provide a name for your mock functions, which will be +displayed instead of "jest.fn()" in test error output. Use this if you want to +be able to quickly identify the mock function reporting an error in your test +output. ```javascript -const myMockFn = jest.fn() +const myMockFn = jest + .fn() .mockReturnValue('default') .mockImplementation(scalar => 42 + scalar) .mockName('add42'); @@ -255,16 +260,17 @@ expect(mockFunc.mock.calls.length).toBeGreaterThan(0); expect(mockFunc.mock.calls).toContain([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] -); +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. +// in the same order, with the same arguments. It will also assert on the name. expect(mockFunc.mock.calls).toEqual([[arg1, arg2]]); expect(mockFunc.mock.getMockName()).toBe('a mock name'); ``` diff --git a/docs/MoreResources.md b/docs/MoreResources.md index de7c7231e601..68a6feebede7 100644 --- a/docs/MoreResources.md +++ b/docs/MoreResources.md @@ -3,22 +3,38 @@ id: more-resources title: More Resources --- -By now you should have a good idea of how Jest can make it easy to test your applications. If you're interested in learning more, here's some related stuff you might want to check out. +By now you should have a good idea of how Jest can make it easy to 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 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/facebook/jest/tree/master/examples) folder on GitHub. You can also learn from the excellent tests used by the [React](https://github.com/facebook/react/tree/master/src/renderers/__tests__), [Relay](https://github.com/facebook/relay/tree/master/packages/react-relay/modern/__tests__), and [React Native](https://github.com/facebook/react-native/tree/master/Libraries/Animated/src/__tests__) projects. +You will find a number of example test cases in the +[`examples`](https://github.com/facebook/jest/tree/master/examples) folder on +GitHub. You can also learn from the excellent tests used by the +[React](https://github.com/facebook/react/tree/master/src/renderers/__tests__), +[Relay](https://github.com/facebook/relay/tree/master/packages/react-relay/modern/__tests__), +and +[React Native](https://github.com/facebook/react-native/tree/master/Libraries/Animated/src/__tests__) +projects. ### Join the community -Ask questions and find answers from other Jest users like you. [Reactiflux](http://www.reactiflux.com/) is a Discord chat where a lot of Jest discussion happens. Check out the [#jest](https://discordapp.com/channels/102860784329052160/103622435865104384) channel. +Ask questions and find answers from other Jest users like you. +[Reactiflux](http://www.reactiflux.com/) is a Discord chat where a lot of Jest +discussion happens. Check out the +[#jest](https://discordapp.com/channels/102860784329052160/103622435865104384) +channel. -Follow the [Jest Twitter account](https://twitter.com/fbjest) and [blog](/jest/blog/) to find out what's happening in the world of Jest. +Follow the [Jest Twitter account](https://twitter.com/fbjest) and +[blog](/jest/blog/) to find out what's happening in the world of Jest. diff --git a/docs/SetupAndTeardown.md b/docs/SetupAndTeardown.md index 7a8b6687a866..6dac737a282f 100644 --- a/docs/SetupAndTeardown.md +++ b/docs/SetupAndTeardown.md @@ -3,13 +3,19 @@ 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. +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`. +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: +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(() => { @@ -29,7 +35,11 @@ test('city database has San Juan', () => { }); ``` -`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: +`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(() => { @@ -39,9 +49,13 @@ beforeEach(() => { ### 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 just do it inline. Jest provides `beforeAll` and `afterAll` to handle this situation. +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 just +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: +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(() => { @@ -63,9 +77,13 @@ test('city database has San Juan', () => { ### Scoping -By default, the `before` and `after` blocks apply to every test in a file. You can also group tests together using a `describe` block. When they are inside a `describe` block, the `before` and `after` blocks only apply to the tests within that `describe` block. +By default, the `before` and `after` blocks apply to every test in a file. You +can also group tests together using a `describe` block. When they are inside a +`describe` block, the `before` and `after` blocks only apply 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: +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 @@ -99,7 +117,9 @@ describe('matching cities to foods', () => { ### 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. In Jest it's simple to run only one test - just temporarily change that `test` command to a `test.only`: +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. In Jest it's simple to run +only one test - just temporarily change that `test` command to a `test.only`: ```js test.only('this will be the only test that runs', () => { @@ -111,4 +131,8 @@ test('this test will not run', () => { }); ``` -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 just logs data. +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 just logs data. diff --git a/docs/SnapshotTesting.md b/docs/SnapshotTesting.md index fbb9649b98e5..e33bacd0e67c 100644 --- a/docs/SnapshotTesting.md +++ b/docs/SnapshotTesting.md @@ -3,13 +3,23 @@ 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. +Snapshot tests are a very useful tool whenever you want to make sure your UI +does not change unexpectedly. -A typical snapshot test case for a mobile app renders a UI component, takes a screenshot, then compares it to a reference image stored alongside the test. The test will fail if the two images do not match: either the change is unexpected, or the screenshot needs to be updated to the new version of the UI component. +A typical snapshot test case for a mobile app renders a UI component, takes a +screenshot, then compares it to a reference image stored alongside the test. The +test will fail if the two images do not match: either the change is unexpected, +or the screenshot 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/facebook/jest/blob/master/examples/snapshot/__tests__/link.react.test.js) for a simple [Link component](https://github.com/facebook/jest/blob/master/examples/snapshot/Link.react.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/facebook/jest/blob/master/examples/snapshot/__tests__/link.react.test.js) +for a simple +[Link component](https://github.com/facebook/jest/blob/master/examples/snapshot/Link.react.js): ```javascript import React from 'react'; @@ -17,14 +27,16 @@ import Link from '../Link.react'; import renderer from 'react-test-renderer'; it('renders correctly', () => { - const tree = renderer.create( - Facebook - ).toJSON(); + const tree = renderer + .create(Facebook) + .toJSON(); expect(tree).toMatchSnapshot(); }); ``` -The first time this test is run, Jest creates a [snapshot file](https://github.com/facebook/jest/blob/master/examples/snapshot/__tests__/__snapshots__/link.react.test.js.snap) that looks like this: +The first time this test is run, Jest creates a +[snapshot file](https://github.com/facebook/jest/blob/master/examples/snapshot/__tests__/__snapshots__/link.react.test.js.snap) +that looks like this: ```javascript exports[`renders correctly 1`] = ` @@ -39,22 +51,41 @@ 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/master/packages/pretty-format) to make snapshots human-readable during code review. On subsequent test runs Jest will simply 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 that should be fixed, or the implementation has changed and the snapshot needs to be updated. - -More information on how snapshot testing works and why we built it can be found on the [release blog post](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html). 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. +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/master/packages/pretty-format) +to make snapshots human-readable during code review. On subsequent test runs +Jest will simply 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 that should be fixed, or the implementation has changed and the +snapshot needs to be updated. + +More information on how snapshot testing works and why we built it can be found +on the +[release blog post](https://facebook.github.io/jest/blog/2016/07/27/jest-14.html). +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. +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. +One such situation can arise if we intentionally change the address the Link +component in our example is pointing to. ```javascript // Updated test case with a Link to a different address it('renders correctly', () => { - const tree = renderer.create( - Instagram - ).toJSON(); + const tree = renderer + .create(Instagram) + .toJSON(); expect(tree).toMatchSnapshot(); }); ``` @@ -63,67 +94,127 @@ In that case, Jest will print this output: ![](/jest/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. +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: +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: ``` 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. +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. +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/master/examples/snapshot), modifying the `Link` component, and running Jest. +You can try out this functionality by cloning the +[snapshot example](https://github.com/facebook/jest/tree/master/examples/snapshot), +modifying the `Link` component, and running Jest. ### Tests Should Be Deterministic -Your tests should be deterministic. That is, 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. +Your tests should be deterministic. That is, 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/master/examples/snapshot/Clock.react.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/facebook/jest/blob/master/examples/snapshot/Clock.react.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: ``` 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. +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. ### Snapshots are not written automatically on Continuous Integration systems (CI) -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. +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. ## Frequently Asked Questions ### 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 as 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. +Yes, all snapshot files should be committed alongside the modules they are +covering and their tests. They should be considered as 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](TutorialReacte.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/master/integration_tests/__tests__/console.test.js) in the Jest repo. +[React](TutorialReacte.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/master/integration_tests/__tests__/console.test.js) +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](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html#why-snapshot-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](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html#why-snapshot-testing). ### Does snapshot testing substitute 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 providing additional value and making 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. +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 providing +additional value and making 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. +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 to update the snapshot file by running Jest and inspecting the result. +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 to 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 figuring out whether the output of the modules covered by tests is changed, rather than giving guidance to design the code in the first place. +Although it is possible to write snapshot files manually, that is usually not +approachable. Snapshots help figuring 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 snapshots testing? diff --git a/docs/TestingAsyncCode.md b/docs/TestingAsyncCode.md index 009490be8028..72abbbd4febc 100644 --- a/docs/TestingAsyncCode.md +++ b/docs/TestingAsyncCode.md @@ -3,15 +3,21 @@ 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. +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. ### Callbacks The most common asynchronous pattern is callbacks. -For example, let's say that you have a `fetchData(callback)` function that fetches some data and calls `callback(data)` when it is complete. You want to test that this returned data is just the string `'peanut butter'`. +For example, let's say that you have a `fetchData(callback)` function that +fetches some data and calls `callback(data)` when it is complete. You want to +test that this returned data is just 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: +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! @@ -24,9 +30,12 @@ test('the data is peanut butter', () => { }); ``` -The problem is that the test will complete as soon as `fetchData` completes, before ever calling the 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. +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 => { @@ -39,13 +48,18 @@ test('the data is peanut butter', done => { }); ``` -If `done()` is never called, the test will fail, which is what you want to happen. +If `done()` is never called, the test will fail, which is what you want to +happen. ### Promises -If your code uses promises, there is a simpler way to handle asynchronous tests. Just return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail. +If your code uses promises, there is a simpler way to handle asynchronous tests. +Just return a promise from your test, and Jest will wait for that promise to +resolve. If the promise is rejected, the test will automatically fail. -For example, let's say that `fetchData`, instead of using a callback, returns a promise that is supposed to resolve to the string `'peanut butter'`. We could test it with: +For example, let's say that `fetchData`, instead of using a callback, 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', () => { @@ -56,23 +70,27 @@ test('the data is peanut butter', () => { }); ``` -Be sure to return the promise - if you omit this `return` statement, your test will complete before `fetchData` completes. +Be sure to return the promise - if you omit this `return` statement, your test +will complete before `fetchData` completes. -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. +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') - ); + return fetchData().catch(e => expect(e).toMatch('error')); }); ``` ### `.resolves` / `.rejects` + ##### available in Jest **20.0.0+** -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. +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', () => { @@ -81,9 +99,12 @@ test('the data is peanut butter', () => { }); ``` -Be sure to return the assertion—if you omit this `return` statement, your test will complete before `fetchData` completes. +Be sure to return the assertion—if you omit this `return` statement, your test +will complete before `fetchData` completes. -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. +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', () => { @@ -94,7 +115,9 @@ test('the fetch fails with an error', () => { ### Async/Await -Alternatively, you can use `async` and `await` in your tests. To write an async test, just use the `async` keyword in front of the function passed to `test`. For example, the same `fetchData` scenario can be tested with: +Alternatively, you can use `async` and `await` in your tests. To write an async +test, just 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 () => { @@ -113,7 +136,8 @@ test('the fetch fails with an error', async () => { }); ``` -Of course, you can combine `async` and `await` with `.resolves` or `.rejects` (available in Jest **20.0.0+**). +Of course, you can combine `async` and `await` with `.resolves` or `.rejects` +(available in Jest **20.0.0+**). ```js test('the data is peanut butter', async () => { @@ -127,6 +151,9 @@ test('the fetch fails with an error', async () => { }); ``` -In these cases, `async` and `await` are effectively just syntactic sugar for the same logic as the promises example uses. +In these cases, `async` and `await` are effectively just syntactic sugar for the +same logic as the promises example uses. -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 makes your tests simpler. +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 makes your tests simpler. diff --git a/docs/TestingFrameworks.md b/docs/TestingFrameworks.md index 1be55c186b23..80b17216a24c 100644 --- a/docs/TestingFrameworks.md +++ b/docs/TestingFrameworks.md @@ -3,26 +3,36 @@ id: testing-frameworks title: Testing Web Frameworks --- -Although Jest may be considered a React-specific test runner, in fact it 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 other popular JS libraries. +Although Jest may be considered a React-specific test runner, in fact it 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 other popular JS libraries. ## 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)) +* [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)) +* [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)) ## Angular -* [Testing Angular faster with Jest](https://www.xfive.co/blog/testing-angular-faster-jest/) by Michał Pierzchała ([@thymikee](https://twitter.com/thymikee)) +* [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)) +* [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](http://redux.js.org/docs/recipes/WritingTests.html) by Redux docs +* [Writing Tests](http://redux.js.org/docs/recipes/WritingTests.html) by Redux + docs diff --git a/docs/TimerMocks.md b/docs/TimerMocks.md index 8568c332bf7e..a9c6c317b930 100644 --- a/docs/TimerMocks.md +++ b/docs/TimerMocks.md @@ -5,7 +5,8 @@ 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. +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=5gVv10J4nio) ```javascript @@ -38,7 +39,8 @@ test('waits 1 second before ending the game', () => { }); ``` -Here we enable fake timers by calling `jest.useFakeTimers();`. This mocks out setTimeout and other timer functions with mock functions. +Here we enable fake timers by calling `jest.useFakeTimers();`. This mocks out +setTimeout and other timer functions with mock functions. ## Run All Timers @@ -47,22 +49,22 @@ 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 - test('calls the callback after 1 second', () => { - const timerGame = require('../timerGame'); - const callback = jest.fn(); +test('calls the callback after 1 second', () => { + const timerGame = require('../timerGame'); + const callback = jest.fn(); - timerGame(callback); + timerGame(callback); - // At this point in time, the callback should not have been called yet - expect(callback).not.toBeCalled(); + // 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(); + // Fast-forward until all timers have been executed + jest.runAllTimers(); - // Now our callback should have been called! - expect(callback).toBeCalled(); - expect(callback.mock.calls.length).toBe(1); - }); + // Now our callback should have been called! + expect(callback).toBeCalled(); + expect(callback.mock.calls.length).toBe(1); +}); ``` ## Run Pending Timers @@ -87,7 +89,6 @@ function infiniteTimerGame(callback) { setTimeout(() => { infiniteTimerGame(callback); }, 10000); - }, 1000); } @@ -128,9 +129,16 @@ describe('infiniteTimerGame', () => { ``` ## Advance Timers by Time + ##### renamed from `runTimersToTime` to `advanceTimersByTime` in Jest **21.3.0** -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 timeframe, 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. +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 timeframe, 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 // timerGame.js diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index 55196894086a..e37635fd565a 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -9,7 +9,8 @@ Uh oh, something went wrong? Use this guide to resolve issues with Jest. Try using the debugging support built into Node. -Place a `debugger;` statement in any of your tests, and then, in your project's directory, run: +Place a `debugger;` statement in any of your tests, and then, in your project's +directory, run: ``` node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] @@ -17,20 +18,37 @@ 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), simply 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. Simply 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 simply 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 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. +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), simply 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. Simply 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 simply 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 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). +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: + ``` node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] or on Windows @@ -38,21 +56,24 @@ node --inspect-brk ./node_modules/jest/bin/jest.js --runInBand [any other argume ``` 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 - }, + "type": "node", + "request": "attach", + "name": "Attach", + "port": 9229 + } ] } ``` -To automatically launch and attach to a process running your tests, use the following configuration: +To automatically launch and attach to a process running your tests, use the +following configuration: + ```json { "version": "0.2.0", @@ -73,7 +94,9 @@ To automatically launch and attach to a process running your tests, use the foll } ``` -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: +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 { @@ -84,15 +107,8 @@ If you are using Facebook's [`create-react-app`](https://github.com/facebookincu "type": "node", "request": "launch", "runtimeExecutable": "${workspaceRoot}/node_modules/.bin/react-scripts", - "runtimeArgs": [ - "--inspect-brk", - "test" - ], - "args": [ - "--runInBand", - "--no-cache", - "--env=jsdom" - ], + "runtimeArgs": ["--inspect-brk", "test"], + "args": ["--runInBand", "--no-cache", "--env=jsdom"], "cwd": "${workspaceRoot}", "protocol": "inspector", "console": "integratedTerminal", @@ -102,23 +118,34 @@ If you are using Facebook's [`create-react-app`](https://github.com/facebookincu } ``` -More information on Node debugging can be found [here](https://nodejs.org/api/debugger.html). +More information on Node debugging can be found +[here](https://nodejs.org/api/debugger.html). ### Debugging in WebStorm -The easiest way to debug Jest tests in [WebStorm](https://www.jetbrains.com/webstorm/) is using `Jest run/debug configuration`. It will launch tests and automatically attach debugger. -In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and select `Jest`. Optionally specify the Jest configuration file, additional options, and environment variables. Save the configuration, put the breakpoints in the code, then click the green debug icon to start debugging. +The easiest way to debug Jest tests in +[WebStorm](https://www.jetbrains.com/webstorm/) is using `Jest run/debug +configuration`. It will launch tests and automatically attach debugger. + +In the WebStorm menu `Run` select `Edit Configurations...`. Then click `+` and +select `Jest`. Optionally specify the Jest configuration file, additional +options, and environment variables. Save the configuration, put the breakpoints +in the code, then click the green debug icon to start debugging. -If you are using Facebook's [`create-react-app`](https://github.com/facebookincubator/create-react-app), in the Jest run/debug configuration specify the path to the `react-scripts` package in the Jest package field and add `--env=jsdom` to the Jest options field. +If you are using Facebook's +[`create-react-app`](https://github.com/facebookincubator/create-react-app), in +the Jest run/debug configuration specify the path to the `react-scripts` package +in the Jest package field and add `--env=jsdom` to the Jest options field. ### 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). +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 @@ -130,11 +157,11 @@ If a promise doesn't resolve at all, this error might be thrown: Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example -`global.Promise = require.requireActual('promise');` and/or consolidate the -used Promise libraries to a single one. +`global.Promise = require.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` +by calling `jest.setTimeout` ``` jest.setTimeout(10000); // 10 second timeout @@ -142,21 +169,26 @@ 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`. +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.html). +Also see +[watchman troubleshooting](https://facebook.github.io/watchman/docs/troubleshooting.html). ### 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) +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). -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/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. -In order to do this you can run tests in the same thread using [`--runInBand`](CLI.md#runinband): +In order to do this you can run tests in the same thread using +[`--runInBand`](CLI.md#runinband): ```bash # Using Jest CLI @@ -166,8 +198,10 @@ jest --runInBand npm 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. +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 @@ -178,9 +212,23 @@ npm test -- --maxWorkers=4 ``` ### Tests are slow when leveraging automocking -Whether via [`automock: true`](configuration.html#automock-boolean) in config or lots of [`jest.mock('my-module')`](jest-object.html#jestmockmodulename-factory-options) calls in tests, automocking has a performance cost that can add up in large projects. The more dependencies a module has, the more work Jest has to do to mock it. Something that can offset this performance cost significantly is adding a code transformer that moves `import` or `require` calls from the top of a module, where they are always executed, down into the body of the module, where they are usually not executed. This can lower the number of modules Jest has to load when running your tests by a considerable amount. -To transform `import` statements, there is [babel-plugin-transform-inline-imports-commonjs](https://github.com/zertosh/babel-plugin-transform-inline-imports-commonjs), and to transform `require` statements, there is [Facebook's `inline-requires` babel plugin](https://github.com/facebook/fbjs/blob/master/packages/babel-preset-fbjs/plugins/inline-requires.js), which is part of the `babel-preset-fbjs` package. +Whether via [`automock: true`](configuration.html#automock-boolean) in config or +lots of +[`jest.mock('my-module')`](jest-object.html#jestmockmodulename-factory-options) +calls in tests, automocking has a performance cost that can add up in large +projects. The more dependencies a module has, the more work Jest has to do to +mock it. Something that can offset this performance cost significantly is adding +a code transformer that moves `import` or `require` calls from the top of a +module, where they are always executed, down into the body of the module, where +they are usually not executed. This can lower the number of modules Jest has to +load when running your tests by a considerable amount. + +To transform `import` statements, there is +[babel-plugin-transform-inline-imports-commonjs](https://github.com/zertosh/babel-plugin-transform-inline-imports-commonjs), +and to transform `require` statements, there is +[Facebook's `inline-requires` babel plugin](https://github.com/facebook/fbjs/blob/master/packages/babel-preset-fbjs/plugins/inline-requires.js), +which is part of the `babel-preset-fbjs` package. ### I'm using npm3 and my node_modules aren't properly loading. @@ -216,7 +264,8 @@ import foo from './foo'; // foo is not mocked! ``` -See the [Getting Started]GettingStarted.md#using-babel) guide on how to enable babel support. +See the [Getting Started]GettingStarted.md#using-babel) guide on how to enable +babel support. ### I upgraded to Jest 0.9.0 and my tests are now failing? @@ -234,7 +283,11 @@ upgrade to the latest stable release of Node. The minimum supported version is ### `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`. +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`. ### Still unresolved? diff --git a/docs/TutorialAsync.md b/docs/TutorialAsync.md index 840e78ef8c66..19c254e89984 100644 --- a/docs/TutorialAsync.md +++ b/docs/TutorialAsync.md @@ -3,10 +3,12 @@ id: tutorial-async title: An Async Example --- -First, enable Babel support in Jest as documented in the [Getting Started](GettingStarted.md#using-babel) guide. +First, enable Babel support in Jest as documented in the +[Getting Started](GettingStarted.md#using-babel) guide. + +Let's implement a simple module that fetches user data from an API and returns +the user name. -Let's implement a simple module that fetches user data from an API and -returns the user name. ```js // user.js import request from './request'; @@ -33,16 +35,16 @@ export default function request(url) { // This module is being mocked in __mocks__/request.js http.get({path: url}, response => { let data = ''; - response.on('data', _data => data += _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: +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 // __mocks__/request.js @@ -55,15 +57,19 @@ 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.', - }) + () => + users[userID] + ? resolve(users[userID]) + : reject({ + error: 'User with ' + userID + ' not found.', + }), ); }); } ``` Now let's write a test for our async functionality. + ```js // __tests__/user-test.js jest.mock('../request'); @@ -77,14 +83,18 @@ it('works with promises', () => { }); ``` -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. +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` + ##### available in Jest **20.0.0+** -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. +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', () => { @@ -95,8 +105,8 @@ it('works with resolves', () => { ### `async`/`await` -Writing tests using the `async`/`await` syntax is easy. Here is -how you'd write the same examples from before: +Writing tests using the `async`/`await` syntax is easy. Here is how you'd write +the same examples from before: ```js // async/await can be used. @@ -114,12 +124,14 @@ it('works with async/await and resolves', async () => { ``` To enable async/await in your project, install -[`babel-preset-env`](http://babeljs.io/docs/plugins/preset-env/) -and enable the feature in your `.babelrc` file. +[`babel-preset-env`](http://babeljs.io/docs/plugins/preset-env/) and enable the +feature in your `.babelrc` 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: +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. @@ -128,7 +140,7 @@ test('tests error with promises', async () => { return user.getUserName(2).catch(e => expect(e).toEqual({ error: 'User with 2 not found.', - }) + }), ); }); @@ -146,9 +158,11 @@ it('tests error with async/await', async () => { ``` ### `.rejects` + ##### available in Jest **20.0.0+** -The`.rejects` helper works like the `.resolves` helper. If the promise is fulfilled, the test will automatically fail. +The`.rejects` helper works like the `.resolves` helper. If the promise is +fulfilled, the test will automatically fail. ```js // Testing for async errors using `.rejects`. diff --git a/docs/TutorialReact.md b/docs/TutorialReact.md index 92ba5d07719b..09d62dd65d3c 100644 --- a/docs/TutorialReact.md +++ b/docs/TutorialReact.md @@ -10,11 +10,19 @@ applications. ### Setup with Create React App -If you are just getting started with React, we recommend using [Create React App](https://github.com/facebookincubator/create-react-app). It is ready to use and [ships with Jest](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#running-tests)! You don't need to do any extra steps for setup, and can head straight to the next section. +If you are just getting started with React, we recommend using +[Create React App](https://github.com/facebookincubator/create-react-app). It is +ready to use and +[ships with Jest](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#running-tests)! +You don't need to do any extra steps for setup, and can head straight to the +next section. ### 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). +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 @@ -22,7 +30,9 @@ Run npm install --save-dev jest babel-jest babel-preset-es2015 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: +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 // package.json @@ -53,7 +63,8 @@ Your `package.json` should look something like this (where `` i ### Snapshot Testing -Let's create a [snapshot test](SnapshotTesting.md) for a Link component that renders hyperlinks: +Let's create a [snapshot test](SnapshotTesting.md) for a Link component that +renders hyperlinks: ```javascript // Link.react.js @@ -65,7 +76,6 @@ const STATUS = { }; export default class Link extends React.Component { - constructor(props) { super(props); @@ -91,16 +101,17 @@ export default class Link extends React.Component { className={this.state.class} href={this.props.page || '#'} onMouseEnter={this._onMouseEnter} - onMouseLeave={this._onMouseLeave}> + onMouseLeave={this._onMouseLeave} + > {this.props.children} ); } - } ``` -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: +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: ```javascript // Link.react-test.js @@ -110,7 +121,7 @@ import renderer from 'react-test-renderer'; test('Link changes the class when hovered', () => { const component = renderer.create( - Facebook + Facebook, ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); @@ -164,16 +175,25 @@ 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 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 next time you run the tests, the rendered output will be compared to the +previously created snapshot. The snapshot should be committed along 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/master/examples/snapshot). ### DOM Testing -If you'd like to assert, and manipulate your rendered components you can use [Enzyme](http://airbnb.io/enzyme/) or React's [TestUtils](http://facebook.github.io/react/docs/test-utils.html). We use Enzyme for this example. +If you'd like to assert, and manipulate your rendered components you can use +[Enzyme](http://airbnb.io/enzyme/) or React's +[TestUtils](http://facebook.github.io/react/docs/test-utils.html). We use Enzyme +for this example. -You have to run `npm install --save-dev enzyme` to use Enzyme. If you are using a React below version 15.5.0, you will also need to install `react-addons-test-utils`. +You have to run `npm install --save-dev enzyme` to use Enzyme. If you are using +a React below version 15.5.0, you will also need to install +`react-addons-test-utils`. Let's implement a simple checkbox which swaps between two labels: @@ -183,7 +203,6 @@ Let's implement a simple checkbox which swaps between two labels: import React from 'react'; export default class CheckboxWithLabel extends React.Component { - constructor(props) { super(props); this.state = {isChecked: false}; @@ -212,7 +231,9 @@ export default class CheckboxWithLabel extends React.Component { } ``` -We use Enzyme's [shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this example. +We use Enzyme's +[shallow renderer](http://airbnb.io/enzyme/docs/api/shallow.html) in this +example. ```javascript // __tests__/CheckboxWithLabel-test.js @@ -223,9 +244,7 @@ import CheckboxWithLabel from '../CheckboxWithLabel'; test('CheckboxWithLabel changes the text after click', () => { // Render a checkbox with label in the document - const checkbox = shallow( - - ); + const checkbox = shallow(); expect(checkbox.text()).toEqual('Off'); @@ -240,7 +259,8 @@ The code for this example is available at ### 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: +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: ```javascript // custom-transformer.js @@ -263,11 +283,14 @@ module.exports = { }; ``` -Don't forget to install the `babel-core` and `babel-preset-jest` packages for this example to work. +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"}`. +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: +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'); diff --git a/docs/TutorialReactNative.md b/docs/TutorialReactNative.md index 6d27a82470f7..78fabb5bc6d0 100644 --- a/docs/TutorialReactNative.md +++ b/docs/TutorialReactNative.md @@ -3,14 +3,21 @@ id: tutorial-react-native title: Testing React Native Apps --- -At Facebook, we use Jest to test [React Native](http://facebook.github.io/react-native/) -applications. +At Facebook, we use Jest to test +[React Native](http://facebook.github.io/react-native/) 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://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.12zbnbgwc) and [Part 2: Jest – Redux Snapshots for your Actions and Reducers](https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-ii-redux-snapshots-for-your-actions-and-reducers-8559f6f8050b). +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://blog.callstack.io/unit-testing-react-native-with-the-new-jest-i-snapshots-come-into-play-68ba19b1b9fe#.12zbnbgwc) +and +[Part 2: Jest – Redux Snapshots for your Actions and Reducers](https://blog.callstack.io/unit-testing-react-native-with-the-new-jest-ii-redux-snapshots-for-your-actions-and-reducers-8559f6f8050b). ## 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: +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 // package.json "scripts": { @@ -21,22 +28,21 @@ Starting from react-native version 0.38, a Jest setup is included by default whe } ``` -*Note: 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.* +_Note: 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._ Simply run `npm test` to run tests with Jest. ## 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: +Let's create a [snapshot test](SnapshotTesting.md) for a small intro component +with a few views and text components and some styles: ```javascript // Intro.js import React, {Component} from 'react'; -import { - StyleSheet, - Text, - View, -} from 'react-native'; +import {StyleSheet, Text, View} from 'react-native'; const styles = StyleSheet.create({ container: { @@ -61,9 +67,7 @@ export default class Intro extends Component { render() { return ( - - Welcome to React Native! - + Welcome to React Native! This is a React Native snapshot test. @@ -73,7 +77,8 @@ export default class Intro extends Component { } ``` -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: +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: ```javascript // __tests__/Intro-test.js @@ -85,9 +90,7 @@ import Intro from '../Intro'; import renderer from 'react-test-renderer'; test('renders correctly', () => { - const tree = renderer.create( - - ).toJSON(); + const tree = renderer.create().toJSON(); expect(tree).toMatchSnapshot(); }); ``` @@ -130,24 +133,40 @@ 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 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 next time you run the tests, the rendered output will be compared to the +previously created snapshot. The snapshot should be committed along 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/master/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. +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. +`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.html#transformignorepatterns-array-string) option can be used to whitelist or blacklist files from being transformed with babel. Many react-native npm modules unfortunately don't pre-compile their source code before publishing. +The +[`transformIgnorePatterns`](configuration.html#transformignorepatterns-array-string) +option can be used to whitelist or blacklist files from being transformed with +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 whitelisting modules other than react-native: +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 whitelisting modules other than +react-native: ```json "transformIgnorePatterns": [ @@ -157,11 +176,17 @@ By default the jest-react-native preset only processes the project's own source ### setupFiles -If you'd like to provide additional configuration for every test file, the [`setupFiles` configuration option](configuration.html#setupfiles-array) can be used to specify setup scripts. +If you'd like to provide additional configuration for every test file, the +[`setupFiles` configuration option](configuration.html#setupfiles-array) can be +used to specify setup scripts. ### moduleNameMapper -The [`moduleNameMapper`](configuration.html#modulenamemapper-object-string-string) 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: +The +[`moduleNameMapper`](configuration.html#modulenamemapper-object-string-string) +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": { @@ -173,17 +198,25 @@ The [`moduleNameMapper`](configuration.html#modulenamemapper-object-string-strin ### 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. +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: +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 `