diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md index 6a5a5b635016..9d57dd096076 100644 --- a/.github/ISSUE_TEMPLATE.md +++ b/.github/ISSUE_TEMPLATE.md @@ -1,4 +1,3 @@ ## 👉 [Please follow one of these issue templates](https://github.com/facebook/jest/issues/new/choose) 👈 -Note: to keep the backlog clean and actionable, issues may be immediately closed -if they do not follow one of the above issue templates. +Note: to keep the backlog clean and actionable, issues may be immediately closed if they do not follow one of the above issue templates. diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md index 97172c45ff0b..19e8f78d8e75 100644 --- a/.github/ISSUE_TEMPLATE/bug.md +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -18,8 +18,7 @@ A clear and concise description of what you expected to happen. ## Link to repl or repo (highly encouraged) -Please provide either a [repl.it demo](https://repl.it/languages/jest) or a -minimal repository on GitHub. +Please provide either a [repl.it demo](https://repl.it/languages/jest) or a minimal repository on GitHub. Issues without a reproduction link are likely to stall. diff --git a/.github/ISSUE_TEMPLATE/feature.md b/.github/ISSUE_TEMPLATE/feature.md index a6d9680634ce..1c2d645e5a57 100644 --- a/.github/ISSUE_TEMPLATE/feature.md +++ b/.github/ISSUE_TEMPLATE/feature.md @@ -18,12 +18,10 @@ Please provide an example for how this feature would be used. ## Pitch -Why does this feature belong in the -[Jest core platform](https://www.youtube.com/watch?v=NtjyeojAOBs)? +Why does this feature belong in the [Jest core platform](https://www.youtube.com/watch?v=NtjyeojAOBs)? Common feature proposals that do not typically make it to core: -* New matchers (see - [jest-extended](https://github.com/jest-community/jest-extended)) +* New matchers (see [jest-extended](https://github.com/jest-community/jest-extended)) * Changes to the default reporter (use custom reporters instead) * Changes to node/jsdom test environments (use custom environments instead) diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md index 8c4ba8f48a34..e7562ee67679 100644 --- a/.github/ISSUE_TEMPLATE/question.md +++ b/.github/ISSUE_TEMPLATE/question.md @@ -12,5 +12,4 @@ For questions or help please see: * [The Jest help page](https://facebook.github.io/jest/en/help.html) * [Our discord channel in Reactiflux](https://discord.gg/MWRhKCj) -* The [jestjs](https://stackoverflow.com/questions/tagged/jestjs) tag on - [StackOverflow](https://stackoverflow.com/questions/ask) +* The [jestjs](https://stackoverflow.com/questions/tagged/jestjs) tag on [StackOverflow](https://stackoverflow.com/questions/ask) diff --git a/.github/ISSUE_TEMPLATE/regression.md b/.github/ISSUE_TEMPLATE/regression.md index fc367a605ed7..637753d00535 100644 --- a/.github/ISSUE_TEMPLATE/regression.md +++ b/.github/ISSUE_TEMPLATE/regression.md @@ -24,8 +24,7 @@ A clear and concise description of what you expected to happen. ## Link to repl or repo (highly encouraged) -Please provide either a [repl.it demo](https://repl.it/languages/jest) or a -minimal repository on GitHub. +Please provide either a [repl.it demo](https://repl.it/languages/jest) or a minimal repository on GitHub. Issues without a reproduction link are likely to stall. diff --git a/.github/SUPPORT.md b/.github/SUPPORT.md index 6404a09955de..99d7aa87a791 100644 --- a/.github/SUPPORT.md +++ b/.github/SUPPORT.md @@ -1,3 +1 @@ -Please note this issue tracker is not a help forum. We recommend using -[StackOverflow](https://stackoverflow.com/questions/tagged/jest) or our -[discord channel](https://discord.gg/MWRhKCj) for questions. +Please note this issue tracker is not a help forum. We recommend using [StackOverflow](https://stackoverflow.com/questions/tagged/jest) or our [discord channel](https://discord.gg/MWRhKCj) for questions. diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b0847c078ec..0601102265c2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,831 +4,488 @@ ### Features -* `[expect]` Expose `getObjectSubset`, `iterableEquality`, and `subsetEquality` - ([#6210](https://github.com/facebook/jest/pull/6210)) -* `[jest-snapshot]` Add snapshot property matchers - ([#6210](https://github.com/facebook/jest/pull/6210)) -* `[jest-config]` Support jest-preset.js files within Node modules - ([#6185](https://github.com/facebook/jest/pull/6185)) -* `[jest-cli]` Add `--detectOpenHandles` flag which enables Jest to potentially - track down handles keeping it open after tests are complete. - ([#6130](https://github.com/facebook/jest/pull/6130)) -* `[jest-jasmine2]` Add data driven testing based on `jest-each` - ([#6102](https://github.com/facebook/jest/pull/6102)) -* `[jest-matcher-utils]` Change "suggest to equal" message to be more advisory - ([#6103](https://github.com/facebook/jest/issues/6103)) -* `[jest-message-util]` Don't ignore messages with `vendor` anymore - ([#6117](https://github.com/facebook/jest/pull/6117)) -* `[jest-validate]` Get rid of `jest-config` dependency - ([#6067](https://github.com/facebook/jest/pull/6067)) -* `[jest-validate]` Adds option to inject `deprecationEntries` - ([#6067](https://github.com/facebook/jest/pull/6067)) -* `[jest-snapshot]` [**BREAKING**] Concatenate name of test, optional snapshot - name and count ([#6015](https://github.com/facebook/jest/pull/6015)) -* `[jest-runtime]` Allow for transform plugins to skip the definition process - method if createTransformer method was defined. - ([#5999](https://github.com/facebook/jest/pull/5999)) -* `[expect]` Add stack trace for async errors - ([#6008](https://github.com/facebook/jest/pull/6008)) -* `[jest-jasmine2]` Add stack trace for timeouts - ([#6008](https://github.com/facebook/jest/pull/6008)) -* `[jest-jasmine2]` Add stack trace for thrown non-`Error`s - ([#6008](https://github.com/facebook/jest/pull/6008)) -* `[jest-runtime]` Prevent modules from marking themselves as their own parent - ([#5235](https://github.com/facebook/jest/issues/5235)) -* `[jest-mock]` Add support for auto-mocking generator functions - ([#5983](https://github.com/facebook/jest/pull/5983)) -* `[expect]` Add support for async matchers -  ([#5919](https://github.com/facebook/jest/pull/5919)) -* `[expect]` Suggest toContainEqual - ([#5948](https://github.com/facebook/jest/pull/5953)) -* `[jest-config]` Export Jest's default options - ([#5948](https://github.com/facebook/jest/pull/5948)) -* `[jest-editor-support]` Move `coverage` to `ProjectWorkspace.collectCoverage` - ([#5929](https://github.com/facebook/jest/pull/5929)) -* `[jest-editor-support]` Add `coverage` option to runner - ([#5836](https://github.com/facebook/jest/pull/5836)) -* `[jest-haste-map]` Support extracting dynamic `import`s - ([#5883](https://github.com/facebook/jest/pull/5883)) -* `[expect]` Improve output format for mismatchedArgs in mock/spy calls. - ([#5846](https://github.com/facebook/jest/pull/5846)) -* `[jest-cli]` Add support for using `--coverage` in combination with watch - mode, `--onlyChanged`, `--findRelatedTests` and more - ([#5601](https://github.com/facebook/jest/pull/5601)) -* `[jest-jasmine2]` [**BREAKING**] Adds error throwing and descriptive errors to - `it`/ `test` for invalid arguments. `[jest-circus]` Adds error throwing and - descriptive errors to `it`/ `test` for invalid arguments - ([#5558](https://github.com/facebook/jest/pull/5558)) -* `[jest-matcher-utils]` Add `isNot` option to `matcherHint` function - ([#5512](https://github.com/facebook/jest/pull/5512)) -* `[jest-config]` Add `` to runtime files not found error report - ([#5693](https://github.com/facebook/jest/pull/5693)) -* `[expect]` Make toThrow matcher pass only if Error object is returned from - promises ([#5670](https://github.com/facebook/jest/pull/5670)) -* `[expect]` Add isError to utils - ([#5670](https://github.com/facebook/jest/pull/5670)) -* `[expect]` Add inverse matchers (`expect.not.arrayContaining`, etc., - [#5517](https://github.com/facebook/jest/pull/5517)) -* `[expect]` `expect.extend` now also extends asymmetric matchers - ([#5503](https://github.com/facebook/jest/pull/5503)) -* `[jest-mock]` Update `spyOnProperty` to support spying on the prototype chain - ([#5753](https://github.com/facebook/jest/pull/5753)) -* `[jest-mock]` Add tracking of return values in the `mock` property - ([#5752](https://github.com/facebook/jest/pull/5752)) -* `[jest-mock]` Add tracking of thrown errors in the `mock` property - ([#5764](https://github.com/facebook/jest/pull/5764)) -* `[expect]`Add nthCalledWith spy matcher - ([#5605](https://github.com/facebook/jest/pull/5605)) -* `[jest-cli]` Add `isSerial` property that runners can expose to specify that - they can not run in parallel - ([#5706](https://github.com/facebook/jest/pull/5706)) -* `[expect]` Add `.toBeCalledTimes` and `toHaveBeenNthCalledWith` aliases - ([#5826](https://github.com/facebook/jest/pull/5826)) -* `[jest-cli]` Interactive Snapshot Mode improvements - ([#5864](https://github.com/facebook/jest/pull/5864)) -* `[jest-editor-support]` Add `no-color` option to runner - ([#5909](https://github.com/facebook/jest/pull/5909)) -* `[jest-jasmine2]` Pretty-print non-Error object errors - ([#5980](https://github.com/facebook/jest/pull/5980)) -* `[jest-message-util]` Include column in stack frames - ([#5889](https://github.com/facebook/jest/pull/5889)) -* `[expect]` Introduce toStrictEqual - ([#6032](https://github.com/facebook/jest/pull/6032)) -* `[expect]` Add return matchers - ([#5879](https://github.com/facebook/jest/pull/5879)) -* `[jest-cli]` Improve snapshot summaries - ([#6181](https://github.com/facebook/jest/pull/6181)) -* `[expect]` Include custom mock names in error messages - ([#6199](https://github.com/facebook/jest/pull/6199)) -* `[jest-diff]` Support returning diff from oneline strings - ([#6221](https://github.com/facebook/jest/pull/6221)) -* `[expect]` Improve return matchers - ([#6172](https://github.com/facebook/jest/pull/6172)) -* `[jest-cli]` Overhaul watch plugin hooks names - ([#6249](https://github.com/facebook/jest/pull/6249)) -* `[jest-mock]` Include tracked call results in serialized mock - ([#6244](https://github.com/facebook/jest/pull/6244)) +* `[expect]` Expose `getObjectSubset`, `iterableEquality`, and `subsetEquality` ([#6210](https://github.com/facebook/jest/pull/6210)) +* `[jest-snapshot]` Add snapshot property matchers ([#6210](https://github.com/facebook/jest/pull/6210)) +* `[jest-config]` Support jest-preset.js files within Node modules ([#6185](https://github.com/facebook/jest/pull/6185)) +* `[jest-cli]` Add `--detectOpenHandles` flag which enables Jest to potentially track down handles keeping it open after tests are complete. ([#6130](https://github.com/facebook/jest/pull/6130)) +* `[jest-jasmine2]` Add data driven testing based on `jest-each` ([#6102](https://github.com/facebook/jest/pull/6102)) +* `[jest-matcher-utils]` Change "suggest to equal" message to be more advisory ([#6103](https://github.com/facebook/jest/issues/6103)) +* `[jest-message-util]` Don't ignore messages with `vendor` anymore ([#6117](https://github.com/facebook/jest/pull/6117)) +* `[jest-validate]` Get rid of `jest-config` dependency ([#6067](https://github.com/facebook/jest/pull/6067)) +* `[jest-validate]` Adds option to inject `deprecationEntries` ([#6067](https://github.com/facebook/jest/pull/6067)) +* `[jest-snapshot]` [**BREAKING**] Concatenate name of test, optional snapshot name and count ([#6015](https://github.com/facebook/jest/pull/6015)) +* `[jest-runtime]` Allow for transform plugins to skip the definition process method if createTransformer method was defined. ([#5999](https://github.com/facebook/jest/pull/5999)) +* `[expect]` Add stack trace for async errors ([#6008](https://github.com/facebook/jest/pull/6008)) +* `[jest-jasmine2]` Add stack trace for timeouts ([#6008](https://github.com/facebook/jest/pull/6008)) +* `[jest-jasmine2]` Add stack trace for thrown non-`Error`s ([#6008](https://github.com/facebook/jest/pull/6008)) +* `[jest-runtime]` Prevent modules from marking themselves as their own parent ([#5235](https://github.com/facebook/jest/issues/5235)) +* `[jest-mock]` Add support for auto-mocking generator functions ([#5983](https://github.com/facebook/jest/pull/5983)) +* `[expect]` Add support for async matchers  ([#5919](https://github.com/facebook/jest/pull/5919)) +* `[expect]` Suggest toContainEqual ([#5948](https://github.com/facebook/jest/pull/5953)) +* `[jest-config]` Export Jest's default options ([#5948](https://github.com/facebook/jest/pull/5948)) +* `[jest-editor-support]` Move `coverage` to `ProjectWorkspace.collectCoverage` ([#5929](https://github.com/facebook/jest/pull/5929)) +* `[jest-editor-support]` Add `coverage` option to runner ([#5836](https://github.com/facebook/jest/pull/5836)) +* `[jest-haste-map]` Support extracting dynamic `import`s ([#5883](https://github.com/facebook/jest/pull/5883)) +* `[expect]` Improve output format for mismatchedArgs in mock/spy calls. ([#5846](https://github.com/facebook/jest/pull/5846)) +* `[jest-cli]` Add support for using `--coverage` in combination with watch mode, `--onlyChanged`, `--findRelatedTests` and more ([#5601](https://github.com/facebook/jest/pull/5601)) +* `[jest-jasmine2]` [**BREAKING**] Adds error throwing and descriptive errors to `it`/ `test` for invalid arguments. `[jest-circus]` Adds error throwing and descriptive errors to `it`/ `test` for invalid arguments ([#5558](https://github.com/facebook/jest/pull/5558)) +* `[jest-matcher-utils]` Add `isNot` option to `matcherHint` function ([#5512](https://github.com/facebook/jest/pull/5512)) +* `[jest-config]` Add `` to runtime files not found error report ([#5693](https://github.com/facebook/jest/pull/5693)) +* `[expect]` Make toThrow matcher pass only if Error object is returned from promises ([#5670](https://github.com/facebook/jest/pull/5670)) +* `[expect]` Add isError to utils ([#5670](https://github.com/facebook/jest/pull/5670)) +* `[expect]` Add inverse matchers (`expect.not.arrayContaining`, etc., [#5517](https://github.com/facebook/jest/pull/5517)) +* `[expect]` `expect.extend` now also extends asymmetric matchers ([#5503](https://github.com/facebook/jest/pull/5503)) +* `[jest-mock]` Update `spyOnProperty` to support spying on the prototype chain ([#5753](https://github.com/facebook/jest/pull/5753)) +* `[jest-mock]` Add tracking of return values in the `mock` property ([#5752](https://github.com/facebook/jest/pull/5752)) +* `[jest-mock]` Add tracking of thrown errors in the `mock` property ([#5764](https://github.com/facebook/jest/pull/5764)) +* `[expect]`Add nthCalledWith spy matcher ([#5605](https://github.com/facebook/jest/pull/5605)) +* `[jest-cli]` Add `isSerial` property that runners can expose to specify that they can not run in parallel ([#5706](https://github.com/facebook/jest/pull/5706)) +* `[expect]` Add `.toBeCalledTimes` and `toHaveBeenNthCalledWith` aliases ([#5826](https://github.com/facebook/jest/pull/5826)) +* `[jest-cli]` Interactive Snapshot Mode improvements ([#5864](https://github.com/facebook/jest/pull/5864)) +* `[jest-editor-support]` Add `no-color` option to runner ([#5909](https://github.com/facebook/jest/pull/5909)) +* `[jest-jasmine2]` Pretty-print non-Error object errors ([#5980](https://github.com/facebook/jest/pull/5980)) +* `[jest-message-util]` Include column in stack frames ([#5889](https://github.com/facebook/jest/pull/5889)) +* `[expect]` Introduce toStrictEqual ([#6032](https://github.com/facebook/jest/pull/6032)) +* `[expect]` Add return matchers ([#5879](https://github.com/facebook/jest/pull/5879)) +* `[jest-cli]` Improve snapshot summaries ([#6181](https://github.com/facebook/jest/pull/6181)) +* `[expect]` Include custom mock names in error messages ([#6199](https://github.com/facebook/jest/pull/6199)) +* `[jest-diff]` Support returning diff from oneline strings ([#6221](https://github.com/facebook/jest/pull/6221)) +* `[expect]` Improve return matchers ([#6172](https://github.com/facebook/jest/pull/6172)) +* `[jest-cli]` Overhaul watch plugin hooks names ([#6249](https://github.com/facebook/jest/pull/6249)) +* `[jest-mock]` Include tracked call results in serialized mock ([#6244](https://github.com/facebook/jest/pull/6244)) ### Fixes -* `[jest-cli]` Fix stdin encoding to utf8 for watch plugins. - ([#6253](https://github.com/facebook/jest/issues/6253)) -* `[expect]` Better detection of DOM Nodes for equality - ([#6246](https://github.com/facebook/jest/pull/6246)) -* `[jest-cli]` Fix misleading action description for F key when in "only failed - tests" mode. ([#6167](https://github.com/facebook/jest/issues/6167)) -* `[jest-worker]` Stick calls to workers before processing them - ([#6073](https://github.com/facebook/jest/pull/6073)) -* `[babel-plugin-jest-hoist]` Allow using `console` global variable - ([#6075](https://github.com/facebook/jest/pull/6075)) -* `[jest-jasmine2]` Always remove node core message from assert stack traces - ([#6055](https://github.com/facebook/jest/pull/6055)) -* `[expect]` Add stack trace when `expect.assertions` and `expect.hasAssertions` - causes test failures. ([#5997](https://github.com/facebook/jest/pull/5997)) -* `[jest-runtime]` Throw a more useful error when trying to require modules - after the test environment is torn down - ([#5888](https://github.com/facebook/jest/pull/5888)) -* `[jest-mock]` [**BREAKING**] Replace timestamps with `invocationCallOrder` - ([#5867](https://github.com/facebook/jest/pull/5867)) -* `[jest-jasmine2]` Install `sourcemap-support` into normal runtime to catch - runtime errors ([#5945](https://github.com/facebook/jest/pull/5945)) -* `[jest-jasmine2]` Added assertion error handling inside `afterAll hook` - ([#5884](https://github.com/facebook/jest/pull/5884)) -* `[jest-cli]` Remove the notifier actions in case of failure when not in watch - mode. ([#5861](https://github.com/facebook/jest/pull/5861)) -* `[jest-mock]` Extend .toHaveBeenCalled return message with outcome - ([#5951](https://github.com/facebook/jest/pull/5951)) -* `[jest-runner]` Assign `process.env.JEST_WORKER_ID="1"` when in runInBand mode - ([#5860](https://github.com/facebook/jest/pull/5860)) -* `[jest-cli]` Add descriptive error message when trying to use - `globalSetup`/`globalTeardown` file that doesn't export a function. - ([#5835](https://github.com/facebook/jest/pull/5835)) -* `[expect]` Do not rely on `instanceof RegExp`, since it will not work for - RegExps created inside of a different VM - ([#5729](https://github.com/facebook/jest/pull/5729)) -* `[jest-resolve]` Update node module resolution algorithm to correctly handle - symlinked paths ([#5085](https://github.com/facebook/jest/pull/5085)) -* `[jest-editor-support]` Update `Settings` to use spawn in shell option - ([#5658](https://github.com/facebook/jest/pull/5658)) -* `[jest-cli]` Improve the error message when 2 projects resolve to the same - config ([#5674](https://github.com/facebook/jest/pull/5674)) -* `[jest-runtime]` remove retainLines from coverage instrumentation - ([#5692](https://github.com/facebook/jest/pull/5692)) -* `[jest-cli]` Fix update snapshot issue when using watchAll - ([#5696](https://github.com/facebook/jest/pull/5696)) -* `[expect]` Fix rejects.not matcher - ([#5670](https://github.com/facebook/jest/pull/5670)) -* `[jest-runtime]` Prevent Babel warnings on large files - ([#5702](https://github.com/facebook/jest/pull/5702)) -* `[jest-mock]` Prevent `mockRejectedValue` from causing unhandled rejection - ([#5720](https://github.com/facebook/jest/pull/5720)) -* `[pretty-format]` Handle React fragments better - ([#5816](https://github.com/facebook/jest/pull/5816)) -* `[pretty-format]` Handle formatting of `React.forwardRef` and `Context` - components ([#6093](https://github.com/facebook/jest/pull/6093)) -* `[jest-cli]` Switch collectCoverageFrom back to a string - ([#5914](https://github.com/facebook/jest/pull/5914)) -* `[jest-regex-util]` Fix handling regex symbols in tests path on Windows - ([#5941](https://github.com/facebook/jest/pull/5941)) -* `[jest-util]` Fix handling of NaN/Infinity in mock timer delay - ([#5966](https://github.com/facebook/jest/pull/5966)) -* `[jest-resolve]` Generalise test for package main entries equivalent to ".". - ([#5968](https://github.com/facebook/jest/pull/5968)) -* `[jest-config]` Ensure that custom resolvers are used when resolving the - configuration ([#5976](https://github.com/facebook/jest/pull/5976)) -* `[website]` Fix website docs - ([#5853](https://github.com/facebook/jest/pull/5853)) -* `[expect]` Fix isEqual Set and Map to compare object values and keys - regardless of order ([#6150](https://github.com/facebook/jest/pull/6150)) -* `[pretty-format]` [**BREAKING**] Remove undefined props from React elements - ([#6162](https://github.com/facebook/jest/pull/6162)) -* `[jest-haste-map]` Properly resolve mocked node modules without package.json - defined ([#6232](https://github.com/facebook/jest/pull/6232)) +* `[jest-cli]` Fix stdin encoding to utf8 for watch plugins. ([#6253](https://github.com/facebook/jest/issues/6253)) +* `[expect]` Better detection of DOM Nodes for equality ([#6246](https://github.com/facebook/jest/pull/6246)) +* `[jest-cli]` Fix misleading action description for F key when in "only failed tests" mode. ([#6167](https://github.com/facebook/jest/issues/6167)) +* `[jest-worker]` Stick calls to workers before processing them ([#6073](https://github.com/facebook/jest/pull/6073)) +* `[babel-plugin-jest-hoist]` Allow using `console` global variable ([#6075](https://github.com/facebook/jest/pull/6075)) +* `[jest-jasmine2]` Always remove node core message from assert stack traces ([#6055](https://github.com/facebook/jest/pull/6055)) +* `[expect]` Add stack trace when `expect.assertions` and `expect.hasAssertions` causes test failures. ([#5997](https://github.com/facebook/jest/pull/5997)) +* `[jest-runtime]` Throw a more useful error when trying to require modules after the test environment is torn down ([#5888](https://github.com/facebook/jest/pull/5888)) +* `[jest-mock]` [**BREAKING**] Replace timestamps with `invocationCallOrder` ([#5867](https://github.com/facebook/jest/pull/5867)) +* `[jest-jasmine2]` Install `sourcemap-support` into normal runtime to catch runtime errors ([#5945](https://github.com/facebook/jest/pull/5945)) +* `[jest-jasmine2]` Added assertion error handling inside `afterAll hook` ([#5884](https://github.com/facebook/jest/pull/5884)) +* `[jest-cli]` Remove the notifier actions in case of failure when not in watch mode. ([#5861](https://github.com/facebook/jest/pull/5861)) +* `[jest-mock]` Extend .toHaveBeenCalled return message with outcome ([#5951](https://github.com/facebook/jest/pull/5951)) +* `[jest-runner]` Assign `process.env.JEST_WORKER_ID="1"` when in runInBand mode ([#5860](https://github.com/facebook/jest/pull/5860)) +* `[jest-cli]` Add descriptive error message when trying to use `globalSetup`/`globalTeardown` file that doesn't export a function. ([#5835](https://github.com/facebook/jest/pull/5835)) +* `[expect]` Do not rely on `instanceof RegExp`, since it will not work for RegExps created inside of a different VM ([#5729](https://github.com/facebook/jest/pull/5729)) +* `[jest-resolve]` Update node module resolution algorithm to correctly handle symlinked paths ([#5085](https://github.com/facebook/jest/pull/5085)) +* `[jest-editor-support]` Update `Settings` to use spawn in shell option ([#5658](https://github.com/facebook/jest/pull/5658)) +* `[jest-cli]` Improve the error message when 2 projects resolve to the same config ([#5674](https://github.com/facebook/jest/pull/5674)) +* `[jest-runtime]` remove retainLines from coverage instrumentation ([#5692](https://github.com/facebook/jest/pull/5692)) +* `[jest-cli]` Fix update snapshot issue when using watchAll ([#5696](https://github.com/facebook/jest/pull/5696)) +* `[expect]` Fix rejects.not matcher ([#5670](https://github.com/facebook/jest/pull/5670)) +* `[jest-runtime]` Prevent Babel warnings on large files ([#5702](https://github.com/facebook/jest/pull/5702)) +* `[jest-mock]` Prevent `mockRejectedValue` from causing unhandled rejection ([#5720](https://github.com/facebook/jest/pull/5720)) +* `[pretty-format]` Handle React fragments better ([#5816](https://github.com/facebook/jest/pull/5816)) +* `[pretty-format]` Handle formatting of `React.forwardRef` and `Context` components ([#6093](https://github.com/facebook/jest/pull/6093)) +* `[jest-cli]` Switch collectCoverageFrom back to a string ([#5914](https://github.com/facebook/jest/pull/5914)) +* `[jest-regex-util]` Fix handling regex symbols in tests path on Windows ([#5941](https://github.com/facebook/jest/pull/5941)) +* `[jest-util]` Fix handling of NaN/Infinity in mock timer delay ([#5966](https://github.com/facebook/jest/pull/5966)) +* `[jest-resolve]` Generalise test for package main entries equivalent to ".". ([#5968](https://github.com/facebook/jest/pull/5968)) +* `[jest-config]` Ensure that custom resolvers are used when resolving the configuration ([#5976](https://github.com/facebook/jest/pull/5976)) +* `[website]` Fix website docs ([#5853](https://github.com/facebook/jest/pull/5853)) +* `[expect]` Fix isEqual Set and Map to compare object values and keys regardless of order ([#6150](https://github.com/facebook/jest/pull/6150)) +* `[pretty-format]` [**BREAKING**] Remove undefined props from React elements ([#6162](https://github.com/facebook/jest/pull/6162)) +* `[jest-haste-map]` Properly resolve mocked node modules without package.json defined ([#6232](https://github.com/facebook/jest/pull/6232)) ### Chore & Maintenance -* `[jest-runner]` Move sourcemap installation from `jest-jasmine2` to - `jest-runner` ([#6176](https://github.com/facebook/jest/pull/6176)) -* `[jest-cli]` Use yargs's built-in `version` instead of rolling our own - ([#6215](https://github.com/facebook/jest/pull/6215)) +* `[jest-runner]` Move sourcemap installation from `jest-jasmine2` to `jest-runner` ([#6176](https://github.com/facebook/jest/pull/6176)) +* `[jest-cli]` Use yargs's built-in `version` instead of rolling our own ([#6215](https://github.com/facebook/jest/pull/6215)) * `[docs]` Add explanation on how to mock methods not implemented in JSDOM -* `[jest-jasmine2]` Simplify `Env.execute` and TreeProcessor to setup and clean - resources for the top suite the same way as for all of the children suites - ([#5885](https://github.com/facebook/jest/pull/5885)) -* `[babel-jest]` [**BREAKING**] Always return object from transformer - ([#5991](https://github.com/facebook/jest/pull/5991)) -* `[*]` Run Prettier on compiled output - ([#5858](https://github.com/facebook/jest/pull/3497)) -* `[jest-cli]` Add fileChange hook for plugins - ([#5708](https://github.com/facebook/jest/pull/5708)) -* `[docs]` Add docs on using `jest.mock(...)` - ([#5648](https://github.com/facebook/jest/pull/5648)) -* `[docs]` Mention Jest Puppeteer Preset - ([#5722](https://github.com/facebook/jest/pull/5722)) -* `[docs]` Add jest-community section to website - ([#5675](https://github.com/facebook/jest/pull/5675)) -* `[docs]` Add versioned docs for v22.4 - ([##5733](https://github.com/facebook/jest/pull/#5733)) -* `[docs]` Improve Snapshot Testing Guide - ([#5812](https://github.com/facebook/jest/issues/5812)) -* `[jest-runtime]` [**BREAKING**] Remove `jest.genMockFn` and - `jest.genMockFunction` ([#6173](https://github.com/facebook/jest/pull/6173)) -* `[jest-message-util]` Avoid adding unnecessary indent to blank lines in stack - traces ([#6211](https://github.com/facebook/jest/pull/6211)) +* `[jest-jasmine2]` Simplify `Env.execute` and TreeProcessor to setup and clean resources for the top suite the same way as for all of the children suites ([#5885](https://github.com/facebook/jest/pull/5885)) +* `[babel-jest]` [**BREAKING**] Always return object from transformer ([#5991](https://github.com/facebook/jest/pull/5991)) +* `[*]` Run Prettier on compiled output ([#5858](https://github.com/facebook/jest/pull/3497)) +* `[jest-cli]` Add fileChange hook for plugins ([#5708](https://github.com/facebook/jest/pull/5708)) +* `[docs]` Add docs on using `jest.mock(...)` ([#5648](https://github.com/facebook/jest/pull/5648)) +* `[docs]` Mention Jest Puppeteer Preset ([#5722](https://github.com/facebook/jest/pull/5722)) +* `[docs]` Add jest-community section to website ([#5675](https://github.com/facebook/jest/pull/5675)) +* `[docs]` Add versioned docs for v22.4 ([##5733](https://github.com/facebook/jest/pull/#5733)) +* `[docs]` Improve Snapshot Testing Guide ([#5812](https://github.com/facebook/jest/issues/5812)) +* `[jest-runtime]` [**BREAKING**] Remove `jest.genMockFn` and `jest.genMockFunction` ([#6173](https://github.com/facebook/jest/pull/6173)) +* `[jest-message-util]` Avoid adding unnecessary indent to blank lines in stack traces ([#6211](https://github.com/facebook/jest/pull/6211)) ## 22.4.2 ### Fixes -* `[jest-haste-map]` Recreate Haste map when deserialization fails - ([#5642](https://github.com/facebook/jest/pull/5642)) +* `[jest-haste-map]` Recreate Haste map when deserialization fails ([#5642](https://github.com/facebook/jest/pull/5642)) ## 22.4.1 ### Fixes -* `[jest-haste-map]` Parallelize Watchman calls in crawler - ([#5640](https://github.com/facebook/jest/pull/5640)) -* `[jest-editor-support]` Update TypeScript definitions - ([#5625](https://github.com/facebook/jest/pull/5625)) -* `[babel-jest]` Remove `retainLines` argument to babel. - ([#5594](https://github.com/facebook/jest/pull/5594)) +* `[jest-haste-map]` Parallelize Watchman calls in crawler ([#5640](https://github.com/facebook/jest/pull/5640)) +* `[jest-editor-support]` Update TypeScript definitions ([#5625](https://github.com/facebook/jest/pull/5625)) +* `[babel-jest]` Remove `retainLines` argument to babel. ([#5594](https://github.com/facebook/jest/pull/5594)) ### Features -* `[jest-runtime]` Provide `require.main` property set to module with test suite - ([#5618](https://github.com/facebook/jest/pull/5618)) +* `[jest-runtime]` Provide `require.main` property set to module with test suite ([#5618](https://github.com/facebook/jest/pull/5618)) ### Chore & Maintenance -* `[docs]` Add note about Node version support - ([#5622](https://github.com/facebook/jest/pull/5622)) -* `[docs]` Update to use yarn - ([#5624](https://github.com/facebook/jest/pull/5624)) -* `[docs]` Add how to mock scoped modules to Manual Mocks doc - ([#5638](https://github.com/facebook/jest/pull/5638)) +* `[docs]` Add note about Node version support ([#5622](https://github.com/facebook/jest/pull/5622)) +* `[docs]` Update to use yarn ([#5624](https://github.com/facebook/jest/pull/5624)) +* `[docs]` Add how to mock scoped modules to Manual Mocks doc ([#5638](https://github.com/facebook/jest/pull/5638)) ## 22.4.0 ### Fixes -* `[jest-haste-map]` Overhauls how Watchman crawler works fixing Windows - ([#5615](https://github.com/facebook/jest/pull/5615)) -* `[expect]` Allow matching of Errors against plain objects - ([#5611](https://github.com/facebook/jest/pull/5611)) -* `[jest-haste-map]` Do not read binary files in Haste, even when instructed to - do so ([#5612](https://github.com/facebook/jest/pull/5612)) -* `[jest-cli]` Don't skip matchers for exact files - ([#5582](https://github.com/facebook/jest/pull/5582)) -* `[docs]` Update discord links - ([#5586](https://github.com/facebook/jest/pull/5586)) -* `[jest-runtime]` Align handling of testRegex on Windows between searching for - tests and instrumentation checks - ([#5560](https://github.com/facebook/jest/pull/5560)) -* `[jest-config]` Make it possible to merge `transform` option with preset - ([#5505](https://github.com/facebook/jest/pull/5505)) -* `[jest-util]` Fix `console.assert` behavior in custom & buffered consoles - ([#5576](https://github.com/facebook/jest/pull/5576)) +* `[jest-haste-map]` Overhauls how Watchman crawler works fixing Windows ([#5615](https://github.com/facebook/jest/pull/5615)) +* `[expect]` Allow matching of Errors against plain objects ([#5611](https://github.com/facebook/jest/pull/5611)) +* `[jest-haste-map]` Do not read binary files in Haste, even when instructed to do so ([#5612](https://github.com/facebook/jest/pull/5612)) +* `[jest-cli]` Don't skip matchers for exact files ([#5582](https://github.com/facebook/jest/pull/5582)) +* `[docs]` Update discord links ([#5586](https://github.com/facebook/jest/pull/5586)) +* `[jest-runtime]` Align handling of testRegex on Windows between searching for tests and instrumentation checks ([#5560](https://github.com/facebook/jest/pull/5560)) +* `[jest-config]` Make it possible to merge `transform` option with preset ([#5505](https://github.com/facebook/jest/pull/5505)) +* `[jest-util]` Fix `console.assert` behavior in custom & buffered consoles ([#5576](https://github.com/facebook/jest/pull/5576)) ### Features -* `[docs]` Add MongoDB guide - ([#5571](https://github.com/facebook/jest/pull/5571)) -* `[jest-runtime]` Deprecate mapCoverage option. - ([#5177](https://github.com/facebook/jest/pull/5177)) -* `[babel-jest]` Add option to return sourcemap from the transformer separately - from source. ([#5177](https://github.com/facebook/jest/pull/5177)) -* `[jest-validate]` Add ability to log deprecation warnings for CLI flags. - ([#5536](https://github.com/facebook/jest/pull/5536)) -* `[jest-serializer]` Added new module for serializing. Works using V8 or JSON - ([#5609](https://github.com/facebook/jest/pull/5609)) -* `[docs]` Add a documentation note for project `displayName` configuration - ([#5600](https://github.com/facebook/jest/pull/5600)) +* `[docs]` Add MongoDB guide ([#5571](https://github.com/facebook/jest/pull/5571)) +* `[jest-runtime]` Deprecate mapCoverage option. ([#5177](https://github.com/facebook/jest/pull/5177)) +* `[babel-jest]` Add option to return sourcemap from the transformer separately from source. ([#5177](https://github.com/facebook/jest/pull/5177)) +* `[jest-validate]` Add ability to log deprecation warnings for CLI flags. ([#5536](https://github.com/facebook/jest/pull/5536)) +* `[jest-serializer]` Added new module for serializing. Works using V8 or JSON ([#5609](https://github.com/facebook/jest/pull/5609)) +* `[docs]` Add a documentation note for project `displayName` configuration ([#5600](https://github.com/facebook/jest/pull/5600)) ### Chore & Maintenance -* `[docs]` Update automatic mocks documentation - ([#5630](https://github.com/facebook/jest/pull/5630)) +* `[docs]` Update automatic mocks documentation ([#5630](https://github.com/facebook/jest/pull/5630)) ## jest 22.3.0 ### Fixes -* `[expect]` Add descriptive error message to CalledWith methods when missing - optional arguments ([#5547](https://github.com/facebook/jest/pull/5547)) -* `[jest-cli]` Fix inability to quit watch mode while debugger is still attached - ([#5029](https://github.com/facebook/jest/pull/5029)) -* `[jest-haste-map]` Properly handle platform-specific file deletions - ([#5534](https://github.com/facebook/jest/pull/5534)) +* `[expect]` Add descriptive error message to CalledWith methods when missing optional arguments ([#5547](https://github.com/facebook/jest/pull/5547)) +* `[jest-cli]` Fix inability to quit watch mode while debugger is still attached ([#5029](https://github.com/facebook/jest/pull/5029)) +* `[jest-haste-map]` Properly handle platform-specific file deletions ([#5534](https://github.com/facebook/jest/pull/5534)) ### Features -* `[jest-util]` Add the following methods to the "console" implementations: - `assert`, `count`, `countReset`, `dir`, `dirxml`, `group`, `groupCollapsed`, - `groupEnd`, `time`, `timeEnd` - ([#5514](https://github.com/facebook/jest/pull/5514)) -* `[docs]` Add documentation for interactive snapshot mode - ([#5291](https://github.com/facebook/jest/pull/5291)) -* `[jest-editor-support]` Add watchAll flag - ([#5523](https://github.com/facebook/jest/pull/5523)) -* `[jest-cli]` Support multiple glob patterns for `collectCoverageFrom` - ([#5537](https://github.com/facebook/jest/pull/5537)) -* `[docs]` Add versioned documentation to the website - ([#5541](https://github.com/facebook/jest/pull/5541)) +* `[jest-util]` Add the following methods to the "console" implementations: `assert`, `count`, `countReset`, `dir`, `dirxml`, `group`, `groupCollapsed`, `groupEnd`, `time`, `timeEnd` ([#5514](https://github.com/facebook/jest/pull/5514)) +* `[docs]` Add documentation for interactive snapshot mode ([#5291](https://github.com/facebook/jest/pull/5291)) +* `[jest-editor-support]` Add watchAll flag ([#5523](https://github.com/facebook/jest/pull/5523)) +* `[jest-cli]` Support multiple glob patterns for `collectCoverageFrom` ([#5537](https://github.com/facebook/jest/pull/5537)) +* `[docs]` Add versioned documentation to the website ([#5541](https://github.com/facebook/jest/pull/5541)) ### Chore & Maintenance -* `[jest-config]` Allow `` to be used with `collectCoverageFrom` - ([#5524](https://github.com/facebook/jest/pull/5524)) -* `[filenames]` Standardize files names in "integration-tests" folder - ([#5513](https://github.com/facebook/jest/pull/5513)) +* `[jest-config]` Allow `` to be used with `collectCoverageFrom` ([#5524](https://github.com/facebook/jest/pull/5524)) +* `[filenames]` Standardize files names in "integration-tests" folder ([#5513](https://github.com/facebook/jest/pull/5513)) ## jest 22.2.2 ### Fixes -* `[babel-jest]` Revert "Remove retainLines from babel-jest" - ([#5496](https://github.com/facebook/jest/pull/5496)) -* `[jest-docblock]` Support multiple of the same `@pragma`. - ([#5154](https://github.com/facebook/jest/pull/5502)) +* `[babel-jest]` Revert "Remove retainLines from babel-jest" ([#5496](https://github.com/facebook/jest/pull/5496)) +* `[jest-docblock]` Support multiple of the same `@pragma`. ([#5154](https://github.com/facebook/jest/pull/5502)) ### Features -* `[jest-worker]` Assign a unique id for each worker and pass it to the child - process. It will be available via `process.env.JEST_WORKER_ID` - ([#5494](https://github.com/facebook/jest/pull/5494)) +* `[jest-worker]` Assign a unique id for each worker and pass it to the child process. It will be available via `process.env.JEST_WORKER_ID` ([#5494](https://github.com/facebook/jest/pull/5494)) ### Chore & Maintenance -* `[filenames]` Standardize file names in root - ([#5500](https://github.com/facebook/jest/pull/5500)) +* `[filenames]` Standardize file names in root ([#5500](https://github.com/facebook/jest/pull/5500)) ## jest 22.2.1 ### Fixes -* `[jest-config]` "all" takes precedence over "lastCommit" - ([#5486](https://github.com/facebook/jest/pull/5486)) +* `[jest-config]` "all" takes precedence over "lastCommit" ([#5486](https://github.com/facebook/jest/pull/5486)) ## jest 22.2.0 ### Features -* `[jest-runner]` Move test summary to after coverage report - ([#4512](https://github.com/facebook/jest/pull/4512)) -* `[jest-cli]` Added `--notifyMode` to specify when to be notified. - ([#5125](https://github.com/facebook/jest/pull/5125)) -* `[diff-sequences]` New package compares items in two sequences to find a - **longest common subsequence**. - ([#5407](https://github.com/facebook/jest/pull/5407)) -* `[jest-matcher-utils]` Add `comment` option to `matcherHint` function - ([#5437](https://github.com/facebook/jest/pull/5437)) -* `[jest-config]` Allow lastComit and changedFilesWithAncestor via JSON config - ([#5476](https://github.com/facebook/jest/pull/5476)) -* `[jest-util]` Add deletion to `process.env` as well - ([#5466](https://github.com/facebook/jest/pull/5466)) -* `[jest-util]` Add case-insensitive getters/setters to `process.env` - ([#5465](https://github.com/facebook/jest/pull/5465)) -* `[jest-mock]` Add util methods to create async functions. - ([#5318](https://github.com/facebook/jest/pull/5318)) +* `[jest-runner]` Move test summary to after coverage report ([#4512](https://github.com/facebook/jest/pull/4512)) +* `[jest-cli]` Added `--notifyMode` to specify when to be notified. ([#5125](https://github.com/facebook/jest/pull/5125)) +* `[diff-sequences]` New package compares items in two sequences to find a **longest common subsequence**. ([#5407](https://github.com/facebook/jest/pull/5407)) +* `[jest-matcher-utils]` Add `comment` option to `matcherHint` function ([#5437](https://github.com/facebook/jest/pull/5437)) +* `[jest-config]` Allow lastComit and changedFilesWithAncestor via JSON config ([#5476](https://github.com/facebook/jest/pull/5476)) +* `[jest-util]` Add deletion to `process.env` as well ([#5466](https://github.com/facebook/jest/pull/5466)) +* `[jest-util]` Add case-insensitive getters/setters to `process.env` ([#5465](https://github.com/facebook/jest/pull/5465)) +* `[jest-mock]` Add util methods to create async functions. ([#5318](https://github.com/facebook/jest/pull/5318)) ### Fixes -* `[jest-cli]` Add trailing slash when checking root folder - ([#5464](https://github.com/facebook/jest/pull/5464)) -* `[jest-cli]` Hide interactive mode if there are no failed snapshot tests - ([#5450](https://github.com/facebook/jest/pull/5450)) -* `[babel-jest]` Remove retainLines from babel-jest - ([#5439](https://github.com/facebook/jest/pull/5439)) -* `[jest-cli]` Glob patterns ignore non-`require`-able files (e.g. `README.md`) - ([#5199](https://github.com/facebook/jest/issues/5199)) -* `[jest-mock]` Add backticks support (\`\`) to `mock` a certain package via the - `__mocks__` folder. ([#5426](https://github.com/facebook/jest/pull/5426)) -* `[jest-message-util]` Prevent an `ENOENT` crash when the test file contained a - malformed source-map. ([#5405](https://github.com/facebook/jest/pull/5405)). -* `[jest]` Add `import-local` to `jest` package. - ([#5353](https://github.com/facebook/jest/pull/5353)) -* `[expect]` Support class instances in `.toHaveProperty()` and `.toMatchObject` - matcher. ([#5367](https://github.com/facebook/jest/pull/5367)) -* `[jest-cli]` Fix npm update command for snapshot summary. - ([#5376](https://github.com/facebook/jest/pull/5376), - [5389](https://github.com/facebook/jest/pull/5389/)) -* `[expect]` Make `rejects` and `resolves` synchronously validate its argument. - ([#5364](https://github.com/facebook/jest/pull/5364)) -* `[docs]` Add tutorial page for ES6 class mocks. - ([#5383](https://github.com/facebook/jest/pull/5383)) -* `[jest-resolve]` Search required modules in node_modules and then in custom - paths. ([#5403](https://github.com/facebook/jest/pull/5403)) -* `[jest-resolve]` Get builtin modules from node core. - ([#5411](https://github.com/facebook/jest/pull/5411)) -* `[jest-resolve]` Detect and preserve absolute paths in `moduleDirectories`. Do - not generate additional (invalid) paths by prepending each ancestor of `cwd` - to the absolute path. Additionally, this fixes functionality in Windows OS. - ([#5398](https://github.com/facebook/jest/pull/5398)) +* `[jest-cli]` Add trailing slash when checking root folder ([#5464](https://github.com/facebook/jest/pull/5464)) +* `[jest-cli]` Hide interactive mode if there are no failed snapshot tests ([#5450](https://github.com/facebook/jest/pull/5450)) +* `[babel-jest]` Remove retainLines from babel-jest ([#5439](https://github.com/facebook/jest/pull/5439)) +* `[jest-cli]` Glob patterns ignore non-`require`-able files (e.g. `README.md`) ([#5199](https://github.com/facebook/jest/issues/5199)) +* `[jest-mock]` Add backticks support (\`\`) to `mock` a certain package via the `__mocks__` folder. ([#5426](https://github.com/facebook/jest/pull/5426)) +* `[jest-message-util]` Prevent an `ENOENT` crash when the test file contained a malformed source-map. ([#5405](https://github.com/facebook/jest/pull/5405)). +* `[jest]` Add `import-local` to `jest` package. ([#5353](https://github.com/facebook/jest/pull/5353)) +* `[expect]` Support class instances in `.toHaveProperty()` and `.toMatchObject` matcher. ([#5367](https://github.com/facebook/jest/pull/5367)) +* `[jest-cli]` Fix npm update command for snapshot summary. ([#5376](https://github.com/facebook/jest/pull/5376), [5389](https://github.com/facebook/jest/pull/5389/)) +* `[expect]` Make `rejects` and `resolves` synchronously validate its argument. ([#5364](https://github.com/facebook/jest/pull/5364)) +* `[docs]` Add tutorial page for ES6 class mocks. ([#5383](https://github.com/facebook/jest/pull/5383)) +* `[jest-resolve]` Search required modules in node_modules and then in custom paths. ([#5403](https://github.com/facebook/jest/pull/5403)) +* `[jest-resolve]` Get builtin modules from node core. ([#5411](https://github.com/facebook/jest/pull/5411)) +* `[jest-resolve]` Detect and preserve absolute paths in `moduleDirectories`. Do not generate additional (invalid) paths by prepending each ancestor of `cwd` to the absolute path. Additionally, this fixes functionality in Windows OS. ([#5398](https://github.com/facebook/jest/pull/5398)) ### Chore & Maintenance -* `[jest-util]` Implement watch plugins - ([#5399](https://github.com/facebook/jest/pull/5399)) +* `[jest-util]` Implement watch plugins ([#5399](https://github.com/facebook/jest/pull/5399)) ## jest 22.1.4 ### Fixes -* `[jest-util]` Add "debug" method to "console" implementations - ([#5350](https://github.com/facebook/jest/pull/5350)) -* `[jest-resolve]` Add condition to avoid infinite loop when node module package - main is ".". ([#5344)](https://github.com/facebook/jest/pull/5344) +* `[jest-util]` Add "debug" method to "console" implementations ([#5350](https://github.com/facebook/jest/pull/5350)) +* `[jest-resolve]` Add condition to avoid infinite loop when node module package main is ".". ([#5344)](https://github.com/facebook/jest/pull/5344) ### Features -* `[jest-cli]` `--changedSince`: allow selectively running tests for code - changed since arbitrary revisions. - ([#5312](https://github.com/facebook/jest/pull/5312)) +* `[jest-cli]` `--changedSince`: allow selectively running tests for code changed since arbitrary revisions. ([#5312](https://github.com/facebook/jest/pull/5312)) ## jest 22.1.3 ### Fixes -* `[jest-cli]` Check if the file belongs to the checked project before adding it - to the list, also checking that the file name is not explicitly blacklisted - ([#5341](https://github.com/facebook/jest/pull/5341)) -* `[jest-editor-support]` Add option to spawn command in shell - ([#5340](https://github.com/facebook/jest/pull/5340)) +* `[jest-cli]` Check if the file belongs to the checked project before adding it to the list, also checking that the file name is not explicitly blacklisted ([#5341](https://github.com/facebook/jest/pull/5341)) +* `[jest-editor-support]` Add option to spawn command in shell ([#5340](https://github.com/facebook/jest/pull/5340)) ## jest 22.1.2 ### Fixes -* `[jest-cli]` Check if the file belongs to the checked project before adding it - to the list ([#5335](https://github.com/facebook/jest/pull/5335)) -* `[jest-cli]` Fix `EISDIR` when a directory is passed as an argument to `jest`. - ([#5317](https://github.com/facebook/jest/pull/5317)) -* `[jest-config]` Added restoreMocks config option. - ([#5327](https://github.com/facebook/jest/pull/5327)) +* `[jest-cli]` Check if the file belongs to the checked project before adding it to the list ([#5335](https://github.com/facebook/jest/pull/5335)) +* `[jest-cli]` Fix `EISDIR` when a directory is passed as an argument to `jest`. ([#5317](https://github.com/facebook/jest/pull/5317)) +* `[jest-config]` Added restoreMocks config option. ([#5327](https://github.com/facebook/jest/pull/5327)) ## jest 22.1.1 ### Fixes -* `[*]` Move from "process.exit" to "exit. - ([#5313](https://github.com/facebook/jest/pull/5313)) +* `[*]` Move from "process.exit" to "exit. ([#5313](https://github.com/facebook/jest/pull/5313)) ## jest 22.1.0 ### Features -* `[jest-cli]` Make Jest exit without an error when no tests are found in the - case of `--lastCommit`, `--findRelatedTests`, or `--onlyChanged` options - having been passed to the CLI -* `[jest-cli]` Add interactive snapshot mode - ([#3831](https://github.com/facebook/jest/pull/3831)) +* `[jest-cli]` Make Jest exit without an error when no tests are found in the case of `--lastCommit`, `--findRelatedTests`, or `--onlyChanged` options having been passed to the CLI +* `[jest-cli]` Add interactive snapshot mode ([#3831](https://github.com/facebook/jest/pull/3831)) ### Fixes -* `[jest-cli]` Use `import-local` to support global Jest installations. - ([#5304](https://github.com/facebook/jest/pull/5304)) -* `[jest-runner]` Fix memory leak in coverage reporting - ([#5289](https://github.com/facebook/jest/pull/5289)) -* `[docs]` Update mention of the minimal version of node supported - ([#4947](https://github.com/facebook/jest/issues/4947)) -* `[jest-cli]` Fix missing newline in console message - ([#5308](https://github.com/facebook/jest/pull/5308)) -* `[jest-cli]` `--lastCommit` and `--changedFilesWithAncestor` now take effect - even when `--onlyChanged` is not specified. - ([#5307](https://github.com/facebook/jest/pull/5307)) +* `[jest-cli]` Use `import-local` to support global Jest installations. ([#5304](https://github.com/facebook/jest/pull/5304)) +* `[jest-runner]` Fix memory leak in coverage reporting ([#5289](https://github.com/facebook/jest/pull/5289)) +* `[docs]` Update mention of the minimal version of node supported ([#4947](https://github.com/facebook/jest/issues/4947)) +* `[jest-cli]` Fix missing newline in console message ([#5308](https://github.com/facebook/jest/pull/5308)) +* `[jest-cli]` `--lastCommit` and `--changedFilesWithAncestor` now take effect even when `--onlyChanged` is not specified. ([#5307](https://github.com/facebook/jest/pull/5307)) ### Chore & Maintenance -* `[filenames]` Standardize folder names under `integration-tests/` - ([#5298](https://github.com/facebook/jest/pull/5298)) +* `[filenames]` Standardize folder names under `integration-tests/` ([#5298](https://github.com/facebook/jest/pull/5298)) ## jest 22.0.6 ### Fixes -* `[jest-jasmine2]` Fix memory leak in snapshot reporting - ([#5279](https://github.com/facebook/jest/pull/5279)) -* `[jest-config]` Fix breaking change in `--testPathPattern` - ([#5269](https://github.com/facebook/jest/pull/5269)) -* `[docs]` Document caveat with mocks, Enzyme, snapshots and React 16 - ([#5258](https://github.com/facebook/jest/issues/5258)) +* `[jest-jasmine2]` Fix memory leak in snapshot reporting ([#5279](https://github.com/facebook/jest/pull/5279)) +* `[jest-config]` Fix breaking change in `--testPathPattern` ([#5269](https://github.com/facebook/jest/pull/5269)) +* `[docs]` Document caveat with mocks, Enzyme, snapshots and React 16 ([#5258](https://github.com/facebook/jest/issues/5258)) ## jest 22.0.5 ### Fixes -* `[jest-leak-detector]` Removed the reference to `weak`. Now, parent projects - must install it by hand for the module to work. -* `[expect]` Fail test when the types of `stringContaining` and `stringMatching` - matchers do not match. ([#5069](https://github.com/facebook/jest/pull/5069)) -* `[jest-cli]` Treat dumb terminals as noninteractive - ([#5237](https://github.com/facebook/jest/pull/5237)) -* `[jest-cli]` `jest --onlyChanged --changedFilesWithAncestor` now also works - with git. ([#5189](https://github.com/facebook/jest/pull/5189)) -* `[jest-config]` fix unexpected condition to avoid infinite recursion in - Windows platform. ([#5161](https://github.com/facebook/jest/pull/5161)) -* `[jest-config]` Escape parentheses and other glob characters in `rootDir` - before interpolating with `testMatch`. - ([#4838](https://github.com/facebook/jest/issues/4838)) -* `[jest-regex-util]` Fix breaking change in `--testPathPattern` - ([#5230](https://github.com/facebook/jest/pull/5230)) -* `[expect]` Do not override `Error` stack (with `Error.captureStackTrace`) for - custom matchers. ([#5162](https://github.com/facebook/jest/pull/5162)) -* `[pretty-format]` Pretty format for DOMStringMap and NamedNodeMap - ([#5233](https://github.com/facebook/jest/pull/5233)) -* `[jest-cli]` Use a better console-clearing string on Windows - ([#5251](https://github.com/facebook/jest/pull/5251)) +* `[jest-leak-detector]` Removed the reference to `weak`. Now, parent projects must install it by hand for the module to work. +* `[expect]` Fail test when the types of `stringContaining` and `stringMatching` matchers do not match. ([#5069](https://github.com/facebook/jest/pull/5069)) +* `[jest-cli]` Treat dumb terminals as noninteractive ([#5237](https://github.com/facebook/jest/pull/5237)) +* `[jest-cli]` `jest --onlyChanged --changedFilesWithAncestor` now also works with git. ([#5189](https://github.com/facebook/jest/pull/5189)) +* `[jest-config]` fix unexpected condition to avoid infinite recursion in Windows platform. ([#5161](https://github.com/facebook/jest/pull/5161)) +* `[jest-config]` Escape parentheses and other glob characters in `rootDir` before interpolating with `testMatch`. ([#4838](https://github.com/facebook/jest/issues/4838)) +* `[jest-regex-util]` Fix breaking change in `--testPathPattern` ([#5230](https://github.com/facebook/jest/pull/5230)) +* `[expect]` Do not override `Error` stack (with `Error.captureStackTrace`) for custom matchers. ([#5162](https://github.com/facebook/jest/pull/5162)) +* `[pretty-format]` Pretty format for DOMStringMap and NamedNodeMap ([#5233](https://github.com/facebook/jest/pull/5233)) +* `[jest-cli]` Use a better console-clearing string on Windows ([#5251](https://github.com/facebook/jest/pull/5251)) ### Features -* `[jest-jasmine]` Allowed classes and functions as `describe` names. - ([#5154](https://github.com/facebook/jest/pull/5154)) -* `[jest-jasmine2]` Support generator functions as specs. - ([#5166](https://github.com/facebook/jest/pull/5166)) -* `[jest-jasmine2]` Allow `spyOn` with getters and setters. - ([#5107](https://github.com/facebook/jest/pull/5107)) -* `[jest-config]` Allow configuration objects inside `projects` array - ([#5176](https://github.com/facebook/jest/pull/5176)) -* `[expect]` Add support to `.toHaveProperty` matcher to accept the keyPath - argument as an array of properties/indices. - ([#5220](https://github.com/facebook/jest/pull/5220)) -* `[docs]` Add documentation for .toHaveProperty matcher to accept the keyPath - argument as an array of properties/indices. - ([#5220](https://github.com/facebook/jest/pull/5220)) -* `[jest-runner]` test environments are now passed a new `options` parameter. - Currently this only has the `console` which is the test console that Jest will - expose to tests. ([#5223](https://github.com/facebook/jest/issues/5223)) -* `[jest-environment-jsdom]` pass the `options.console` to a custom instance of - `virtualConsole` so jsdom is using the same console as the test. - ([#5223](https://github.com/facebook/jest/issues/5223)) +* `[jest-jasmine]` Allowed classes and functions as `describe` names. ([#5154](https://github.com/facebook/jest/pull/5154)) +* `[jest-jasmine2]` Support generator functions as specs. ([#5166](https://github.com/facebook/jest/pull/5166)) +* `[jest-jasmine2]` Allow `spyOn` with getters and setters. ([#5107](https://github.com/facebook/jest/pull/5107)) +* `[jest-config]` Allow configuration objects inside `projects` array ([#5176](https://github.com/facebook/jest/pull/5176)) +* `[expect]` Add support to `.toHaveProperty` matcher to accept the keyPath argument as an array of properties/indices. ([#5220](https://github.com/facebook/jest/pull/5220)) +* `[docs]` Add documentation for .toHaveProperty matcher to accept the keyPath argument as an array of properties/indices. ([#5220](https://github.com/facebook/jest/pull/5220)) +* `[jest-runner]` test environments are now passed a new `options` parameter. Currently this only has the `console` which is the test console that Jest will expose to tests. ([#5223](https://github.com/facebook/jest/issues/5223)) +* `[jest-environment-jsdom]` pass the `options.console` to a custom instance of `virtualConsole` so jsdom is using the same console as the test. ([#5223](https://github.com/facebook/jest/issues/5223)) ### Chore & Maintenance -* `[docs]` Describe the order of execution of describe and test blocks. - ([#5217](https://github.com/facebook/jest/pull/5217), - [#5238](https://github.com/facebook/jest/pull/5238)) -* `[docs]` Add a note on `moduleNameMapper` ordering. - ([#5249](https://github.com/facebook/jest/pull/5249)) +* `[docs]` Describe the order of execution of describe and test blocks. ([#5217](https://github.com/facebook/jest/pull/5217), [#5238](https://github.com/facebook/jest/pull/5238)) +* `[docs]` Add a note on `moduleNameMapper` ordering. ([#5249](https://github.com/facebook/jest/pull/5249)) ## jest 22.0.4 ### Fixes -* `[jest-cli]` New line before quitting watch mode. - ([#5158](https://github.com/facebook/jest/pull/5158)) +* `[jest-cli]` New line before quitting watch mode. ([#5158](https://github.com/facebook/jest/pull/5158)) ### Features -* `[babel-jest]` moduleFileExtensions not passed to babel transformer. - ([#5110](https://github.com/facebook/jest/pull/5110)) +* `[babel-jest]` moduleFileExtensions not passed to babel transformer. ([#5110](https://github.com/facebook/jest/pull/5110)) ### Chore & Maintenance -* `[*]` Tweaks to better support Node 4 - ([#5142](https://github.com/facebook/jest/pull/5142)) +* `[*]` Tweaks to better support Node 4 ([#5142](https://github.com/facebook/jest/pull/5142)) ## jest 22.0.2 && 22.0.3 ### Chore & Maintenance -* `[*]` Tweaks to better support Node 4 - ([#5134](https://github.com/facebook/jest/pull/5134)) +* `[*]` Tweaks to better support Node 4 ([#5134](https://github.com/facebook/jest/pull/5134)) ## jest 22.0.1 ### Fixes -* `[jest-runtime]` fix error for test files providing coverage. - ([#5117](https://github.com/facebook/jest/pull/5117)) +* `[jest-runtime]` fix error for test files providing coverage. ([#5117](https://github.com/facebook/jest/pull/5117)) ### Features -* `[jest-config]` Add `forceCoverageMatch` to allow collecting coverage from - ignored files. ([#5081](https://github.com/facebook/jest/pull/5081)) +* `[jest-config]` Add `forceCoverageMatch` to allow collecting coverage from ignored files. ([#5081](https://github.com/facebook/jest/pull/5081)) ## jest 22.0.0 ### Fixes -* `[jest-resolve]` Use `module.builtinModules` as `BUILTIN_MODULES` when it - exists -* `[jest-worker]` Remove `debug` and `inspect` flags from the arguments sent to - the child ([#5068](https://github.com/facebook/jest/pull/5068)) -* `[jest-config]` Use all `--testPathPattern` and `` args in - `testPathPattern` ([#5066](https://github.com/facebook/jest/pull/5066)) -* `[jest-cli]` Do not support `--watch` inside non-version-controlled - environments ([#5060](https://github.com/facebook/jest/pull/5060)) -* `[jest-config]` Escape Windows path separator in testPathPattern CLI arguments - ([#5054](https://github.com/facebook/jest/pull/5054) -* `[jest-jasmine]` Register sourcemaps as node environment to improve - performance with jsdom ([#5045](https://github.com/facebook/jest/pull/5045)) -* `[pretty-format]` Do not call toJSON recursively - ([#5044](https://github.com/facebook/jest/pull/5044)) -* `[pretty-format]` Fix errors when identity-obj-proxy mocks CSS Modules - ([#4935](https://github.com/facebook/jest/pull/4935)) -* `[babel-jest]` Fix support for namespaced babel version 7 - ([#4918](https://github.com/facebook/jest/pull/4918)) -* `[expect]` fix .toThrow for promises - ([#4884](https://github.com/facebook/jest/pull/4884)) -* `[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-cli]` Use `fs.realpathSync.native` if available - ([#5031](https://github.com/facebook/jest/pull/5031)) -* `[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-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-cli]` Fix `--onlyChanged` path case sensitivity on Windows platform - ([#4730](https://github.com/facebook/jest/pull/4730)) -* `[jest-runtime]` Use realpath to match transformers - ([#5000](https://github.com/facebook/jest/pull/5000)) -* `[expect]` [**BREAKING**] Replace identity equality with Object.is in toBe - matcher ([#4917](https://github.com/facebook/jest/pull/4917)) +* `[jest-resolve]` Use `module.builtinModules` as `BUILTIN_MODULES` when it exists +* `[jest-worker]` Remove `debug` and `inspect` flags from the arguments sent to the child ([#5068](https://github.com/facebook/jest/pull/5068)) +* `[jest-config]` Use all `--testPathPattern` and `` args in `testPathPattern` ([#5066](https://github.com/facebook/jest/pull/5066)) +* `[jest-cli]` Do not support `--watch` inside non-version-controlled environments ([#5060](https://github.com/facebook/jest/pull/5060)) +* `[jest-config]` Escape Windows path separator in testPathPattern CLI arguments ([#5054](https://github.com/facebook/jest/pull/5054) +* `[jest-jasmine]` Register sourcemaps as node environment to improve performance with jsdom ([#5045](https://github.com/facebook/jest/pull/5045)) +* `[pretty-format]` Do not call toJSON recursively ([#5044](https://github.com/facebook/jest/pull/5044)) +* `[pretty-format]` Fix errors when identity-obj-proxy mocks CSS Modules ([#4935](https://github.com/facebook/jest/pull/4935)) +* `[babel-jest]` Fix support for namespaced babel version 7 ([#4918](https://github.com/facebook/jest/pull/4918)) +* `[expect]` fix .toThrow for promises ([#4884](https://github.com/facebook/jest/pull/4884)) +* `[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-cli]` Use `fs.realpathSync.native` if available ([#5031](https://github.com/facebook/jest/pull/5031)) +* `[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-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-cli]` Fix `--onlyChanged` path case sensitivity on Windows platform ([#4730](https://github.com/facebook/jest/pull/4730)) +* `[jest-runtime]` Use realpath to match transformers ([#5000](https://github.com/facebook/jest/pull/5000)) +* `[expect]` [**BREAKING**] Replace identity equality with Object.is in toBe matcher ([#4917](https://github.com/facebook/jest/pull/4917)) ### Features -* `[jest-message-util]` Add codeframe to test assertion failures - ([#5087](https://github.com/facebook/jest/pull/5087)) -* `[jest-config]` Add Global Setup/Teardown options - ([#4716](https://github.com/facebook/jest/pull/4716)) -* `[jest-config]` Add `testEnvironmentOptions` to apply to jsdom options or node - context. ([#5003](https://github.com/facebook/jest/pull/5003)) -* `[jest-jasmine2]` Update Timeout error message to `jest.timeout` and display - current timeout value ([#4990](https://github.com/facebook/jest/pull/4990)) -* `[jest-runner]` Enable experimental detection of leaked contexts - ([#4895](https://github.com/facebook/jest/pull/4895)) -* `[jest-cli]` Add combined coverage threshold for directories. - ([#4885](https://github.com/facebook/jest/pull/4885)) -* `[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]` [**BREAKING**] 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-environment-jsdom]` Update JSOM to 11.4, which includes built-in - support for `requestAnimationFrame` - ([#4919](https://github.com/facebook/jest/pull/4919)) -* `[jest-cli]` Hide watch usage output when running on non-interactive - environments ([#4958](https://github.com/facebook/jest/pull/4958)) -* `[jest-snapshot]` Promises support for `toThrowErrorMatchingSnapshot` - ([#4946](https://github.com/facebook/jest/pull/4946)) -* `[jest-cli]` Explain which snapshots are obsolete - ([#5005](https://github.com/facebook/jest/pull/5005)) +* `[jest-message-util]` Add codeframe to test assertion failures ([#5087](https://github.com/facebook/jest/pull/5087)) +* `[jest-config]` Add Global Setup/Teardown options ([#4716](https://github.com/facebook/jest/pull/4716)) +* `[jest-config]` Add `testEnvironmentOptions` to apply to jsdom options or node context. ([#5003](https://github.com/facebook/jest/pull/5003)) +* `[jest-jasmine2]` Update Timeout error message to `jest.timeout` and display current timeout value ([#4990](https://github.com/facebook/jest/pull/4990)) +* `[jest-runner]` Enable experimental detection of leaked contexts ([#4895](https://github.com/facebook/jest/pull/4895)) +* `[jest-cli]` Add combined coverage threshold for directories. ([#4885](https://github.com/facebook/jest/pull/4885)) +* `[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]` [**BREAKING**] 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-environment-jsdom]` Update JSOM to 11.4, which includes built-in support for `requestAnimationFrame` ([#4919](https://github.com/facebook/jest/pull/4919)) +* `[jest-cli]` Hide watch usage output when running on non-interactive environments ([#4958](https://github.com/facebook/jest/pull/4958)) +* `[jest-snapshot]` Promises support for `toThrowErrorMatchingSnapshot` ([#4946](https://github.com/facebook/jest/pull/4946)) +* `[jest-cli]` Explain which snapshots are obsolete ([#5005](https://github.com/facebook/jest/pull/5005)) ### Chore & Maintenance -* `[docs]` Add guide of using with puppeteer - ([#5093](https://github.com/facebook/jest/pull/5093)) -* `[jest-util]` `jest-util` should not depend on `jest-mock` - ([#4992](https://github.com/facebook/jest/pull/4992)) -* `[*]` [**BREAKING**] Drop support for Node.js version 4 - ([#4769](https://github.com/facebook/jest/pull/4769)) -* `[docs]` Wrap code comments at 80 characters - ([#4781](https://github.com/facebook/jest/pull/4781)) -* `[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. +* `[docs]` Add guide of using with puppeteer ([#5093](https://github.com/facebook/jest/pull/5093)) +* `[jest-util]` `jest-util` should not depend on `jest-mock` ([#4992](https://github.com/facebook/jest/pull/4992)) +* `[*]` [**BREAKING**] Drop support for Node.js version 4 ([#4769](https://github.com/facebook/jest/pull/4769)) +* `[docs]` Wrap code comments at 80 characters ([#4781](https://github.com/facebook/jest/pull/4781)) +* `[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. * `[docs]` Include missing dependency in TestEnvironment sample code * `[docs]` Add clarification for hook execution order -* `[docs]` Update `expect.anything()` sample code - ([#5007](https://github.com/facebook/jest/pull/5007)) +* `[docs]` Update `expect.anything()` sample code ([#5007](https://github.com/facebook/jest/pull/5007)) ## 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 @@ -836,126 +493,70 @@ ## 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 @@ -964,376 +565,206 @@ * 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 @@ -1348,71 +779,54 @@ ## 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. @@ -1424,40 +838,33 @@ 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`. @@ -1483,8 +890,7 @@ 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. @@ -1509,42 +915,33 @@ 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. +* 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. +* 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. +* 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. +* 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. @@ -1560,8 +957,7 @@ 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 @@ -1578,30 +974,23 @@ 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. @@ -1626,10 +1015,7 @@ 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. @@ -1654,21 +1040,16 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest 13.0.0 * Added duration of individual tests in verbose mode. -* Added a `browser` config option to properly resolve npm packages with a - browser field in `package.json` if you are writing tests for client side apps +* Added a `browser` config option to properly resolve npm packages with a 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. @@ -1681,21 +1062,16 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest-cli 12.1.0 * Jest is now also published in the `jest` package on npm. -* Added `testRegex` to match for tests outside of specific folders. Deprecated - both `testDirectoryName` and `testFileExtensions`. +* Added `testRegex` to match for tests outside of specific folders. Deprecated both `testDirectoryName` and `testFileExtensions`. * `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-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 `--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. -* Further improved the `lastCalledWith` and `toBeCalledWith` custom matchers. - They now print the most recent calls. +* Further improved the `lastCalledWith` and `toBeCalledWith` custom matchers. They now print the most recent calls. * Fixed jest-haste-map on continuous integration systems. * Fixes for hg/git integration. * Added a re-try for the watchman crawler. @@ -1711,8 +1087,7 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest-cli 12.0.0 -* Reimplemented `node-haste` as `jest-haste-map`: - https://github.com/facebook/jest/pull/896 +* Reimplemented `node-haste` as `jest-haste-map`: https://github.com/facebook/jest/pull/896 * Fixes for the upcoming release of nodejs 6. * Removed global mock caching which caused negative side-effects on test runs. * Updated Jasmine from 2.3.4 to 2.4.1. @@ -1733,31 +1108,20 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## jest-cli 11.0.0, babel-jest 11.0.0 (pre-releases 0.9 to 0.10) -* New implementation of node-haste and rewrite of internal module loading and - resolution. Fixed both startup and runtime performance. - [#599](https://github.com/facebook/jest/pull/599) -* Jasmine 2 is now the default test runner. To keep using Jasmine 1, put - `testRunner: "jasmine1"` into your configuration. -* Added `jest-util`, `jest-mock`, `jest-jasmine1`, `jest-jasmine2`, - `jest-environment-node`, `jest-environment-jsdom` packages. -* Added `babel-jest-preset` and `babel-jest` as packages. `babel-jest` is now - being auto-detected. -* Added `babel-plugin-jest-hoist` which hoists `jest.unmock`, `jest.mock` and - the new `jest.enableAutomock` and `jest.disableAutomock` API. +* New implementation of node-haste and rewrite of internal module loading and resolution. Fixed both startup and runtime performance. [#599](https://github.com/facebook/jest/pull/599) +* Jasmine 2 is now the default test runner. To keep using Jasmine 1, put `testRunner: "jasmine1"` into your configuration. +* Added `jest-util`, `jest-mock`, `jest-jasmine1`, `jest-jasmine2`, `jest-environment-node`, `jest-environment-jsdom` packages. +* Added `babel-jest-preset` and `babel-jest` as packages. `babel-jest` is now being auto-detected. +* Added `babel-plugin-jest-hoist` which hoists `jest.unmock`, `jest.mock` and the new `jest.enableAutomock` and `jest.disableAutomock` API. * Improved `babel-jest` integration and `react-native` testing. * Improved code coverage reporting when using `babel-jest`. -* Added the `jest.mock('moduleName', moduleFactory)` feature. `jest.mock` now - gets hoisted by default. `jest.doMock` was added to explicitly mock a module - without the hoisting feature of `babel-jest`. +* Added the `jest.mock('moduleName', moduleFactory)` feature. `jest.mock` now gets hoisted by default. `jest.doMock` was added to explicitly mock a module without the hoisting feature of `babel-jest`. * Updated jsdom to 8.3.x. * Improved responsiveness of the system while using `--watch`. * 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. -* Added `jest.fn()` and `jest.fn(implementation)` as convenient shorcuts for - `jest.genMockFunction()` and `jest.genMockFunction().mockImplementation()`. +* 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. +* 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. * Added a "no tests found" message if no tests can be found. * Jest sets `process.NODE_ENV` to `test` unless otherwise specified. @@ -1778,8 +1142,7 @@ 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 @@ -1797,61 +1160,43 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html * Added optional support for jasmine2 through the `testRunner` config option. * Fixed mocking support for Map, WeakMap and Set. * `node` was added to the defaults in `moduleFileExtensions`. -* Updated the list of node core modules that are properly being recognized by - the module loader. +* Updated the list of node core modules that are properly being recognized by the module loader. ## 0.7.1 -* Correctly map `process.on` into jsdom environments, fixes a bug introduced in - jest 0.7.0. +* Correctly map `process.on` into jsdom environments, fixes a bug introduced in jest 0.7.0. ## 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. -* 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: +* 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 +* 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. +* Removed `navigator.onLine` and `mockSetReadOnlyProperty` from the global jsdom environment. Use `window.navigator.onLine = true;` in your test setup and `Object.defineProperty` instead. ## 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. +* Modules now receive a `module.parent` field so unmocked modules don't assume they are run directly any longer. ## 0.6.0 -* jest now reports the number of tests that were run instead of the number of - test files. +* jest now reports the number of tests that were run instead of the number of test files. * Added a `--json` option to print test results as JSON. -* Changed the preprocessor API. A preprocessor now receives the script, file and - config. The cache key function receives the script, file and stringified - config to be able to create consistent hashes. +* Changed the preprocessor API. A preprocessor now receives the script, file and config. The cache key function receives the script, file and stringified config to be able to create consistent hashes. * Removed node-worker-pool in favor of node-worker-farm (#540). -* `toEqual` now also checks the internal class name of an object. This fixes - invalid tests like `expect([]).toEqual({})` which were previously passing. -* Added the option to provide map modules to stub modules by providing the - `moduleNameMapper` config option. +* `toEqual` now also checks the internal class name of an object. This fixes invalid tests like `expect([]).toEqual({})` which were previously passing. +* Added the option to provide map modules to stub modules by providing the `moduleNameMapper` config option. * Allow to specify a custom `testRunner` in the configuration (#531). * Added a `--no-cache` option to make it easier to debug preprocessor scripts. * Fix code coverage on windows (#499). ## 0.5.6 -* Cache test run performance and run slowest tests first to maximize worker - utilization +* Cache test run performance and run slowest tests first to maximize worker utilization * Update to jsdom 6.5.0 ## 0.5.5 @@ -1878,8 +1223,7 @@ See https://facebook.github.io/jest/blog/2016/12/15/2016-in-jest.html ## 0.5.0 * Added `--noStackTrace` option to disable stack traces. -* Jest now only works with iojs v2 and up. If you are still using node we - recommend upgrading to iojs or keep using jest 0.4.0. +* Jest now only works with iojs v2 and up. If you are still using node we recommend upgrading to iojs or keep using jest 0.4.0. * Upgraded to jsdom 6.1.0 and removed all the custom jsdom overwrites. ## <=0.4.0 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bbbfbd09604c..41ecc8f264e4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,44 +1,26 @@ # How to Contribute -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. ## Open Development -All work on Jest happens directly on [GitHub](/). Both core team members and -external contributors send pull requests which go through the same review -process. +All work on Jest happens directly on [GitHub](/). Both core team members and external contributors send pull requests which go through the same review process. ### `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… -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: @@ -50,13 +32,9 @@ _Before_ submitting a pull request, please make sure the following is done… 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). +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
+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 @@ -68,8 +46,7 @@ _Before_ submitting a pull request, please make sure the following is done… 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 @@ -78,10 +55,7 @@ _Before_ submitting a pull request, please make sure the following is done… 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](https://www.mercurial-scm.org/) (`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](https://www.mercurial-scm.org/) (`hg`). On macOS, this can be done using [homebrew](http://brew.sh/): `brew install hg`. ```sh brew install hg # maybe @@ -92,35 +66,25 @@ _Before_ submitting a pull request, please make sure the following is done… #### 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. +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. ```sh cd website # Only needed if you are not already in the website directory yarn yarn start ``` -2. You can run a development server to check if the changes you made are being - displayed accurately by running `yarn start` in the website directory. +2. You can run a development server to check if the changes you made are being displayed accurately by running `yarn start` in the website directory. ### 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 @@ -148,11 +112,9 @@ 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 @@ -162,25 +124,19 @@ 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://discord.gg/MWRhKCj) on - [Reactiflux](http://www.reactiflux.com/) +* Discord - [#jest](https://discord.gg/MWRhKCj) on [Reactiflux](http://www.reactiflux.com/) ## Code Conventions @@ -195,5 +151,4 @@ issues; go through the process outlined on that page. ## 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/README.md b/README.md index bae3ef6c86d0..6a217a869f50 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,14 @@ # Jest -[![CircleCI Build Status](https://circleci.com/gh/facebook/jest.svg?style=shield)](https://circleci.com/gh/facebook/jest) -[![Travis Build Status](https://travis-ci.org/facebook/jest.svg?branch=master)](https://travis-ci.org/facebook/jest) -[![Windows Build Status](https://ci.appveyor.com/api/projects/status/8n38o44k585hhvhd/branch/master?svg=true)](https://ci.appveyor.com/project/Daniel15/jest/branch/master) -[![npm version](https://badge.fury.io/js/jest.svg)](http://badge.fury.io/js/jest) -[![Blazing Fast](https://img.shields.io/badge/speed-blazing%20%F0%9F%94%A5-brightgreen.svg)](https://twitter.com/acdlite/status/974390255393505280) -[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) +[![CircleCI Build Status](https://circleci.com/gh/facebook/jest.svg?style=shield)](https://circleci.com/gh/facebook/jest) [![Travis Build Status](https://travis-ci.org/facebook/jest.svg?branch=master)](https://travis-ci.org/facebook/jest) [![Windows Build Status](https://ci.appveyor.com/api/projects/status/8n38o44k585hhvhd/branch/master?svg=true)](https://ci.appveyor.com/project/Daniel15/jest/branch/master) [![npm version](https://badge.fury.io/js/jest.svg)](http://badge.fury.io/js/jest) [![Blazing Fast](https://img.shields.io/badge/speed-blazing%20%F0%9F%94%A5-brightgreen.svg)](https://twitter.com/acdlite/status/974390255393505280) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 🃏 Delightful JavaScript Testing -* **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing - solution. Works out of the box for any React project. +* **👩🏻‍💻 Developer Ready**: Complete and ready to set-up JavaScript testing solution. Works out of the box for any React project. -* **🏃🏽 Instant Feedback**: Fast interactive watch mode runs only test files - related to changed files and is optimized to give signal quickly. +* **🏃🏽 Instant Feedback**: Fast interactive watch mode runs only test files related to changed files and is optimized to give signal quickly. -* **📸 Snapshot Testing**: Capture snapshots of React trees or other - serializable values to simplify testing and to analyze how state changes over - time. +* **📸 Snapshot Testing**: Capture snapshots of React trees or other serializable values to simplify testing and to analyze how state changes over time. ## Getting Started @@ -35,13 +26,9 @@ Or via [`npm`](https://www.npmjs.com/): npm install --save-dev jest ``` -The minimum supported Node version is `v6.0.0` by default. If you need to -support Node 4, refer to the -[Compatibility issues](https://facebook.github.io/jest/docs/en/troubleshooting.html#compatibility-issues) -section. +The minimum supported Node version is `v6.0.0` by default. If you need to support Node 4, refer to the [Compatibility issues](https://facebook.github.io/jest/docs/en/troubleshooting.html#compatibility-issues) section. -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) { @@ -79,45 +66,33 @@ 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](https://facebook.github.io/jest/docs/using-matchers.html). +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](https://facebook.github.io/jest/docs/using-matchers.html). ## Running from command line -You can run Jest directly from the CLI (if it's globally available in your -`PATH`, e.g. by `yarn global add jest`) with variety of useful options. +You can run Jest directly from the CLI (if it's globally available in your `PATH`, e.g. by `yarn global add 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](https://facebook.github.io/jest/docs/cli.html) -page. +If you'd like to learn more about running `jest` through the command line, take a look at the [Jest CLI Options](https://facebook.github.io/jest/docs/cli.html) page. ## Additional Configuration ### Using Babel -[Babel](http://babeljs.io/) is automatically handled by Jest using `babel-jest`. -You don't need install anything extra for using Babel. +[Babel](http://babeljs.io/) is automatically handled by Jest using `babel-jest`. You don't need install anything extra for using Babel. -> Note: If you are using a babel version 7 then you need to install -> `babel-core@^7.0.0-0` and `@babel/core` with the following command: +> Note: If you are using a babel version 7 then you need to install `babel-core@^7.0.0-0` and `@babel/core` with the following command: > > ```bash > yarn add --dev 'babel-core@^7.0.0-0' @babel/core > ``` -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-env`](https://babeljs.io/docs/plugins/preset-env/) 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-env`](https://babeljs.io/docs/plugins/preset-env/) and [`babel-preset-react`](https://babeljs.io/docs/plugins/preset-react/) presets: ```json { @@ -127,14 +102,9 @@ in your project's root folder. For example, if you are using ES6 and 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 ES 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 ES modules with the option `{ "modules": false }`, you have to make sure to turn this on in your test environment. ```json { @@ -147,10 +117,7 @@ You are now set up to use all ES6 features and React specific syntax. } ``` -> 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 @@ -163,22 +130,17 @@ You are now set up to use all ES6 features and React specific syntax. ### Using webpack -Jest can be used in projects that use [webpack](https://webpack.js.org/) to -manage assets, styles, and compilation. webpack does offer some unique -challenges over other tools. Refer to the [webpack guide](docs/Webpack.md) to -get started. +Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. webpack does offer some unique challenges over other tools. Refer to the [webpack guide](docs/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). ## Documentation -Learn more about using -[Jest on the official site!](http://facebook.github.io/jest) +Learn more about using [Jest on the official site!](http://facebook.github.io/jest) * [Getting Started](http://facebook.github.io/jest/docs/en/getting-started.html) * [Guides](http://facebook.github.io/jest/docs/en/snapshot-testing.html) @@ -187,41 +149,27 @@ Learn more about using ## Badge -Show the world you're using _Jest_ → -[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) -[![jest](https://facebook.github.io/jest/img/jest-badge.svg)](https://github.com/facebook/jest) +Show the world you're using _Jest_ → [![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) [![jest](https://facebook.github.io/jest/img/jest-badge.svg)](https://github.com/facebook/jest) ```md -[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) -[![jest](https://facebook.github.io/jest/img/jest-badge.svg)](https://github.com/facebook/jest) +[![tested with jest](https://img.shields.io/badge/tested_with-jest-99424f.svg)](https://github.com/facebook/jest) [![jest](https://facebook.github.io/jest/img/jest-badge.svg)](https://github.com/facebook/jest) ``` ## Contributing -The main purpose of this repository is to continue to evolve Jest, making it -faster and easier to use. Development of Jest happens in the open on GitHub, and -we are grateful to the community for contributing bugfixes and improvements. -Read below to learn how you can take part in improving Jest. +The main purpose of this repository is to continue to evolve Jest, making it faster and easier to use. Development of Jest happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. Read below to learn how you can take part in improving Jest. ### [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. ### [Contributing Guide](CONTRIBUTING.md) -Read our [contributing guide](CONTRIBUTING.md) to learn about our development -process, how to propose bugfixes and improvements, and how to build and test -your changes to Jest. +Read our [contributing guide](CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Jest. ### Good First Issues -To help you get your feet wet and get you familiar with our contribution -process, we have a list of -[good first issues](https://github.com/facebook/jest/labels/Good%20First%20Issue%20%3Awave%3A) -that contain bugs which have a relatively limited scope. This is a great place -to get started. +To help you get your feet wet and get you familiar with our contribution process, we have a list of [good first issues](https://github.com/facebook/jest/labels/Good%20First%20Issue%20%3Awave%3A) that contain bugs which have a relatively limited scope. This is a great place to get started. ### License diff --git a/docs/CLI.md b/docs/CLI.md index 8416dc5952b0..ee8f89e1613d 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -3,10 +3,7 @@ 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: @@ -37,8 +34,7 @@ Run tests related to `path/to/fileA.js` and `path/to/fileB.js`: 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 @@ -51,13 +47,11 @@ 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 yarn -If you run Jest via `yarn test`, you can pass the command line arguments -directly as Jest arguments. +If you run Jest via `yarn test`, you can pass the command line arguments directly as Jest arguments. Instead of: @@ -73,8 +67,7 @@ yarn test -u -t="ColorPicker" ## Using with npm scripts -If you run Jest via `npm test`, you can still use the command line arguments by -inserting a `--` between `npm test` and the Jest arguments. +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: @@ -90,8 +83,7 @@ npm test -- -u -t="ColorPicker" ## Options -_Note: CLI options take precedence over values from the -[Configuration](Configuration.md)._ +_Note: CLI options take precedence over values from the [Configuration](Configuration.md)._ @@ -101,12 +93,7 @@ _Note: CLI options take precedence over values from the ### `jest ` -When you run `jest` with an argument, that argument is treated as a regular -expression to match against files in your project. It is possible to run test -suites by providing a pattern. Only the files that the pattern matches will be -picked up and executed. Depending on your terminal, you may need to quote this -argument: `jest "my.*(complex)?pattern"`. On Windows, you will need to use `/` -as a path separator or escape `\` as `\\`. +When you run `jest` with an argument, that argument is treated as a regular expression to match against files in your project. It is possible to run test suites by providing a pattern. Only the files that the pattern matches will be picked up and executed. Depending on your terminal, you may need to quote this argument: `jest "my.*(complex)?pattern"`. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. ### `--bail` @@ -114,43 +101,29 @@ 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`. ### `--changedFilesWithAncestor` -Runs tests related to the current changes and the changes made in the last -commit. Behaves similarly to `--onlyChanged`. +Runs tests related to the current changes and the changes made in the last commit. Behaves similarly to `--onlyChanged`. ### `--changedSince` -Runs tests related the changes since the provided branch. If the current branch -has diverged from the given branch, then only changes made locally will be -tested. Behaves similarly to `--onlyChanged`. +Runs tests related the changes since the provided branch. If the current branch has diverged from the given branch, then only changes made locally will be tested. Behaves similarly to `--onlyChanged`. ### `--ci` -When this option is provided, Jest will assume it is running in a CI -environment. This changes the behavior when a new snapshot is encountered. -Instead of the regular behavior of storing a new snapshot automatically, it will -fail the test and require Jest to be run with `--updateSnapshot`. +When this option is provided, Jest will assume it is running in a CI environment. This changes the behavior when a new snapshot is encountered. Instead of the regular behavior of storing a new snapshot automatically, it will fail the test and require Jest to be run with `--updateSnapshot`. ### `--clearCache` -Deletes the Jest cache directory and then exits without running tests. Will -delete `cacheDirectory` if the option is passed, or Jest's default cache -directory. The default cache directory can be found by calling -`jest --showConfig`. _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=` -A glob pattern relative to matching the files that coverage info needs -to be collected from. +A glob pattern relative to matching the files that coverage info needs to be collected from. ### `--colors` @@ -158,15 +131,11 @@ 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` @@ -174,16 +143,11 @@ Print debugging info about your Jest config. ### `--detectOpenHandles` -Attempt to collect and print open handles preventing Jest from exiting cleanly. -Use this in cases where you need to use `--forceExit` in order for Jest to exit -to potentially track down the reason. Implemented using -[`async_hooks`](https://nodejs.org/api/async_hooks.html), so it only works in -Node 8 and newer. +Attempt to collect and print open handles preventing Jest from exiting cleanly. Use this in cases where you need to use `--forceExit` in order for Jest to exit to potentially track down the reason. Implemented using [`async_hooks`](https://nodejs.org/api/async_hooks.html), so it only works in Node 8 and newer. ### `--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` @@ -191,21 +155,11 @@ 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. Can be used together with `--coverage` to -include a test coverage for the source files, no duplicate -`--collectCoverageFrom` arguments needed. +Find and run the tests that cover a space separated list of source files that were passed in as arguments. Useful for pre-commit hook integration to run the minimal amount of tests necessary. Can be used together with `--coverage` to include a test coverage for the source files, no duplicate `--collectCoverageFrom` arguments needed. ### `--forceExit` -Force Jest to exit after all tests have completed running. This is useful when -resources set up by test code cannot be adequately cleaned up. _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. You can use `--detectOpenHandles` to help -track it down._ +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. You can use `--detectOpenHandles` to help track it down._ ### `--help` @@ -213,8 +167,7 @@ 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=` @@ -222,26 +175,19 @@ Write test results to a file when the `--json` option is also specified. ### `--lastCommit` -Run all tests affected by file changes in the last commit made. Behaves -similarly to `--onlyChanged`. +Run all tests affected by file changes in the last commit made. Behaves similarly to `--onlyChanged`. ### `--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` @@ -249,15 +195,11 @@ 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). ### `--passWithNoTests` @@ -269,15 +211,11 @@ 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` @@ -289,17 +227,13 @@ Prevent tests from printing messages through the console. ### `--testNamePattern=` -Alias: `-t`. Run only tests with a name that matches the regex. For example, -suppose you want to run only tests related to authorization which will have -names like `"GET /api/posts with auth"`, then you can use `jest -t=auth`. +Alias: `-t`. Run only tests with a name that matches the regex. For example, suppose you want to run only tests related to authorization which will have names like `"GET /api/posts with auth"`, then you can use `jest -t=auth`. -_Note: The regex is matched against the full name, which is a combination of the -test name and all its surrounding describe blocks._ +_Note: The regex is matched against the full name, which is a combination of the test name and all its surrounding describe blocks._ ### `--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. @@ -312,9 +246,7 @@ Note that `column` is 0-indexed while `line` is not. ### `--testPathPattern=` -A regexp pattern string that is matched against all tests paths before executing -the test. On Windows, you will need to use `/` as a path separator or escape `\` -as `\\`. +A regexp pattern string that is matched against all tests paths before executing the test. On Windows, you will need to use `/` as a path separator or escape `\` as `\\`. ### `--testRunner=` @@ -322,9 +254,7 @@ 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` @@ -340,16 +270,12 @@ 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 a147f9b1fdab..4c36920f45fa 100644 --- a/docs/Configuration.md +++ b/docs/Configuration.md @@ -3,11 +3,7 @@ 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 { @@ -40,9 +36,7 @@ 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. ### Defaults @@ -68,9 +62,7 @@ module.exports = { Default: `false` -This option tells Jest that all imported modules in your tests should be mocked -automatically. All modules used in your tests will have a replacement -implementation, keeping the API surface. +This option tells Jest that all imported modules in your tests should be mocked automatically. All modules used in your tests will have a replacement implementation, keeping the API surface. Example: @@ -103,29 +95,21 @@ test('if utils mocked automatically', () => { }); ``` -_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] @@ -133,35 +117,25 @@ 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. ### `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. ### `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. +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. Example: @@ -175,11 +149,9 @@ Example: } ``` -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] @@ -191,42 +163,25 @@ The directory where Jest should output its coverage files. 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/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib) -can be used. +A list of reporter names that Jest uses when writing coverage reports. Any [istanbul reporter](https://github.com/istanbuljs/istanbuljs/tree/master/packages/istanbul-reports/lib) can be used. -_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. Thresholds can be specified as `global`, as a -[glob](https://github.com/isaacs/node-glob#glob-primer), and as a directory or -file path. If thresholds aren't met, jest will fail. Thresholds specified as a -positive number are taken to be the minimum percentage required. Thresholds -specified as a negative number represent the maximum number of uncovered -entities allowed. +This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as `global`, as a [glob](https://github.com/isaacs/node-glob#glob-primer), and as a directory or file path. If thresholds aren't met, jest will fail. Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed. -For example, with the following configuration jest will fail if there is less -than 80% branch, line, and function coverage, or if there are more than 10 -uncovered statements: +For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements: ```json { @@ -244,10 +199,7 @@ uncovered statements: } ``` -If globs or paths are specified alongside `global`, coverage data for matching -paths will be subtracted from overall coverage and thresholds will be applied -independently. Thresholds for globs are applied to all files matching the glob. -If the file specified by path is not found, error is returned. +If globs or paths are specified alongside `global`, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. Thresholds for globs are applied to all files matching the glob. If the file specified by path is not found, error is returned. For example, with the following configuration: @@ -282,10 +234,8 @@ For example, with the following configuration: Jest will fail if: -* The `./src/components` directory has less than 40% branch or statement - coverage. -* One of the files matching the `./src/reducers/**/*.js` glob has less than 90% - statement coverage. +* The `./src/components` directory has less than 40% branch or statement coverage. +* One of the files matching the `./src/reducers/**/*.js` glob has less than 90% statement coverage. * The `./src/api/very-important-module.js` file has less than 100% coverage. * Every remaining file combined has less than 50% coverage (`global`). @@ -293,12 +243,9 @@ Jest will fail if: Default: `['']` -Test files are normally ignored from collecting code coverage. With this option, -you can overwrite this behavior and include otherwise ignored files in code -coverage. +Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage. -For example, if you have tests in source files named with `.t.js` extension as -following: +For example, if you have tests in source files named with `.t.js` extension as following: ```javascript // sum.t.js @@ -331,8 +278,7 @@ 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 { @@ -345,60 +291,45 @@ For example, the following would create a global `__DEV__` variable set to } ``` -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. In -addition the `globals` object must be json-serializable, so it can't be used to -specify global functions. For that you should use `setupFiles`. +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. In addition the `globals` object must be json-serializable, so it can't be used to specify global functions. For that you should use `setupFiles`. ### `globalSetup` [string] Default: `undefined` -This option allows the use of a custom global setup module which exports an -async function that is triggered once before all test suites. +This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. ### `globalTeardown` [string] Default: `undefined` -This option allows the use of a custom global teardown module which exports an -async function that is triggered once after all test suites. +This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. ### `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: @@ -412,36 +343,23 @@ Example: } ``` -The order in which the mappings are defined matters. Patterns are checked one by -one until one fits. The most specific rule should be listed first. +The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. -_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] @@ -462,16 +380,13 @@ Specifies notification mode. Requires `notify: true`. * `success`: send a notification when tests pass. * `change`: send a notification when the status changed. * `success-change`: send a notification when tests pass or once when it fails. -* `failure-success`: send a notification when tests fails or once when it - passes. +* `failure-success`: send a notification when tests fails or once when it passes. ### `preset` [string] Default: `undefined` -A preset that is used as a base for Jest's configuration. A preset should point -to an npm module that exports a `jest-preset.json` or `jest-preset.js` module at -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` or `jest-preset.js` module at its top level. Presets may also be relative filesystem paths. @@ -485,10 +400,7 @@ Presets may also be relative filesystem paths. 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 { @@ -496,15 +408,9 @@ time. } ``` -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. -The projects feature can also be used to run multiple configurations or multiple -[runners](#runner-string). For this purpose you can pass an array of -configuration objects. For example, to run both tests and ESLint (via -[jest-runner-eslint](https://github.com/jest-community/jest-runner-eslint)) in -the same invocation of Jest: +The projects feature can also be used to run multiple configurations or multiple [runners](#runner-string). For this purpose you can pass an array of configuration objects. For example, to run both tests and ESLint (via [jest-runner-eslint](https://github.com/jest-community/jest-runner-eslint)) in the same invocation of Jest: ```json { @@ -521,20 +427,15 @@ the same invocation of Jest: } ``` -_Note: When using multi project runner, it's recommended to add a `displayName` -for each project. This will show the `displayName` of a project next to its -tests._ +_Note: When using multi project runner, it's recommended to add a `displayName` for each project. This will show the `displayName` of a project next to its tests._ ### `reporters` [array] Default: `undefined` -Use this configuration option to add custom reporters to Jest. A custom reporter -is a class that implements `onRunStart`, `onTestStart`, `onTestResult`, -`onRunComplete` methods that will be called when any of those events occurs. +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: @@ -544,8 +445,7 @@ This will override default reporters: } ``` -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 { @@ -553,8 +453,7 @@ provides: } ``` -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 { @@ -565,8 +464,7 @@ as a second argument: } ``` -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: @@ -588,8 +486,7 @@ 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 { @@ -602,35 +499,25 @@ 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` -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: ```json { @@ -643,36 +530,23 @@ argument: } ``` -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. ### `restoreMocks` [boolean] Default: `false` -Automatically restore mock state between every test. Equivalent to calling -`jest.restoreAllMocks()` between each test. This will lead to any mocks having -their fake implementations removed and restores their initial implementation. +Automatically restore mock state between every test. Equivalent to calling `jest.restoreAllMocks()` between each test. This will lead to any mocks having their fake implementations removed and restores their initial implementation. ### `rootDir` [string] -Default: The root of the directory containing your jest's [config file](#) _or_ -the `package.json` _or_ the [`pwd`](http://en.wikipedia.org/wiki/Pwd) if no -`package.json` is found +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`. +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] @@ -680,34 +554,24 @@ 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/"]`._ ### `runner` [string] Default: `"jest-runner"` -This option allows you to use a custom runner instead of Jest's default test -runner. Examples of runners include: +This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include: * [`jest-runner-eslint`](https://github.com/jest-community/jest-runner-eslint) * [`jest-runner-mocha`](https://github.com/rogeliog/jest-runner-mocha) * [`jest-runner-tsc`](https://github.com/azz/jest-runner-tsc) * [`jest-runner-prettier`](https://github.com/keplersj/jest-runner-prettier) -To write a test-runner, export a class with which accepts `globalConfig` in the -constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts `globalConfig` in the constructor, and has a `runTests` method with the signature: ```ts async runTests( @@ -720,48 +584,31 @@ async runTests( ): Promise ``` -If you need to restrict your test-runner to only run in serial rather then being -executed in parallel your class should have the property `isSerial` to be set as -`true`. +If you need to restrict your test-runner to only run in serial rather then being executed in parallel your class should have the property `isSerial` to be set as `true`. ### `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. +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: @@ -780,8 +627,7 @@ module.exports = { `serialize` is a function that serializes a value using existing plugins. -To use `my-serializer-module` as a serializer, configuration would be as -follows: +To use `my-serializer-module` as a serializer, configuration would be as follows: ```json { @@ -816,22 +662,15 @@ 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. -By adding a `@jest-environment` docblock at the top of the file, you can specify -another environment to be used for all tests in that file: +By adding a `@jest-environment` docblock at the top of the file, you can specify another environment to be used for all tests in that file: ```js /** @@ -844,14 +683,9 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test -environment. The module must export a class with `setup`, `teardown` and -`runScript` methods. You can also pass variables from this module to your test -suites by assigning them to `this.global` object – this will make them -available in your test suites as global variables. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. -_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: @@ -895,50 +729,31 @@ beforeAll(() => { Default: `{}` -Test environment options that will be passed to the `testEnvironment`. The -relevant options depend on the environment. For example you can override options -given to [jsdom](https://github.com/tmpvar/jsdom) such as -`{userAgent: "Agent/007"}`. +Test environment options that will be passed to the `testEnvironment`. The relevant options depend on the environment. For example you can override options given to [jsdom](https://github.com/tmpvar/jsdom) such as `{userAgent: "Agent/007"}`. ### `testMatch` [array] (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: @@ -956,9 +771,7 @@ The following is a visualization of the default regex: 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: ```json { @@ -1006,9 +819,7 @@ structure as the first argument and return it: 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: @@ -1021,110 +832,64 @@ 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` 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)_ +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` 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. +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/"]`. -Sometimes it happens (especially in React Native or TypeScript projects) that -3rd party modules are published as untranspiled. Since all files inside -`node_modules` are not transformed by default, Jest will not understand the code -in these modules, resulting in syntax errors. To overcome this, you may use -`transformIgnorePatterns` to whitelist such modules. You'll find a good example -of this use case in -[React Native Guide](http://facebook.github.io/jest/docs/en/tutorial-react-native.html#transformignorepatterns-customization). +Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside `node_modules` are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use `transformIgnorePatterns` to whitelist such modules. You'll find a good example of this use case in [React Native Guide](http://facebook.github.io/jest/docs/en/tutorial-react-native.html#transformignorepatterns-customization). ### `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: `[]` -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/Es6ClassMocks.md b/docs/Es6ClassMocks.md index bde88d4f66bd..8c85f5f0a3bb 100644 --- a/docs/Es6ClassMocks.md +++ b/docs/Es6ClassMocks.md @@ -3,19 +3,13 @@ id: es6-class-mocks title: ES6 Class Mocks --- -Jest can be used to mock ES6 classes that are imported into files you want to -test. +Jest can be used to mock ES6 classes that are imported into files you want to test. -ES6 classes are constructor functions with some syntactic sugar. Therefore, any -mock for an ES6 class must be a function or an actual ES6 class (which is, -again, another function). So you can mock them using -[mock functions](MockFunctions.md). +ES6 classes are constructor functions with some syntactic sugar. Therefore, any mock for an ES6 class must be a function or an actual ES6 class (which is, again, another function). So you can mock them using [mock functions](MockFunctions.md). ## An ES6 Class Example -We'll use a contrived example of a class that plays sound files, `SoundPlayer`, -and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock -`SoundPlayer` in our tests for `SoundPlayerConsumer`. +We'll use a contrived example of a class that plays sound files, `SoundPlayer`, and a consumer class which uses that class, `SoundPlayerConsumer`. We'll mock `SoundPlayer` in our tests for `SoundPlayerConsumer`. ```javascript // sound-player.js @@ -50,19 +44,11 @@ export default class SoundPlayerConsumer { ### Automatic mock -Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can -use to spy on calls to the class constructor and all of its methods. It replaces -the ES6 class with a mock constructor, and replaces all of its methods with -[mock functions](MockFunctions.md) that always return `undefined`. Method calls -are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. +Calling `jest.mock('./sound-player')` returns a useful "automatic mock" you can use to spy on calls to the class constructor and all of its methods. It replaces the ES6 class with a mock constructor, and replaces all of its methods with [mock functions](MockFunctions.md) that always return `undefined`. Method calls are saved in `theAutomaticMock.mock.instances[index].methodName.mock.calls`. -Please note that if you use arrow functions in your classes, they will _not_ be -part of the mock. The reason for that is that arrow functions are not present on -the object's prototype, they are merely properties holding a reference to a -function. +Please note that if you use arrow functions in your classes, they will _not_ be part of the mock. The reason for that is that arrow functions are not present on the object's prototype, they are merely properties holding a reference to a function. -If you don't need to replace the implementation of the class, this is the -easiest option to set up. For example: +If you don't need to replace the implementation of the class, this is the easiest option to set up. For example: ```javascript import SoundPlayer from './sound-player'; @@ -102,9 +88,7 @@ it('We can check if the consumer called a method on the class instance', () => { ### Manual mock -Create a [manual mock](ManualMocks.md) by saving a mock implementation in the -`__mocks__` folder. This allows you to specify the implementation, and it can be -used across test files. +Create a [manual mock](ManualMocks.md) by saving a mock implementation in the `__mocks__` folder. This allows you to specify the implementation, and it can be used across test files. ```javascript // __mocks__/sound-player.js @@ -147,12 +131,9 @@ it('We can check if the consumer called a method on the class instance', () => { ### Calling [`jest.mock()`](JestObjectAPI.md#jestmockmodulename-factory-options) with the module factory parameter -`jest.mock(path, moduleFactory)` takes a **module factory** argument. A module -factory is a function that returns the mock. +`jest.mock(path, moduleFactory)` takes a **module factory** argument. A module factory is a function that returns the mock. -In order to mock a constructor function, the module factory must return a -constructor function. In other words, the module factory must be a function that -returns a function - a higher-order function (HOF). +In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). ```javascript import SoundPlayer from './sound-player'; @@ -164,22 +145,13 @@ jest.mock('./sound-player', () => { }); ``` -A limitation with the factory parameter is that, since calls to `jest.mock()` -are hoisted to the top of the file, it's not possible to first define a variable -and then use it in the factory. An exception is made for variables that start -with the word 'mock'. It's up to you to guarantee that they will be initialized -on time! +A limitation with the factory parameter is that, since calls to `jest.mock()` are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'. It's up to you to guarantee that they will be initialized on time! ### Replacing the mock using [`mockImplementation()`](MockFunctionAPI.md#mockfnmockimplementationfn) or [`mockImplementationOnce()`](MockFunctionAPI.md#mockfnmockimplementationoncefn) -You can replace all of the above mocks in order to change the implementation, -for a single test or all tests, by calling `mockImplementation()` on the -existing mock. +You can replace all of the above mocks in order to change the implementation, for a single test or all tests, by calling `mockImplementation()` on the existing mock. -Calls to jest.mock are hoisted to the top of the code. You can specify a mock -later, e.g. in `beforeAll()`, by calling `mockImplementation()` (or -`mockImplementationOnce()`) on the existing mock instead of using the factory -parameter. This also allows you to change the mock between tests, if needed: +Calls to jest.mock are hoisted to the top of the code. You can specify a mock later, e.g. in `beforeAll()`, by calling `mockImplementation()` (or `mockImplementationOnce()`) on the existing mock instead of using the factory parameter. This also allows you to change the mock between tests, if needed: ```javascript import SoundPlayer from './sound-player'; @@ -205,16 +177,11 @@ describe('When SoundPlayer throws an error', () => { ## In depth: Understanding mock constructor functions -Building your constructor function mock using `jest.fn().mockImplementation()` -makes mocks appear more complicated than they really are. This section shows how -you can create your own simple mocks to illustrate how mocking works. +Building your constructor function mock using `jest.fn().mockImplementation()` makes mocks appear more complicated than they really are. This section shows how you can create your own simple mocks to illustrate how mocking works. ### Manual mock that is another ES6 class -If you define an ES6 class using the same filename as the mocked class in the -`__mocks__` folder, it will serve as the mock. This class will be used in place -of the real class. This allows you to inject a test implementation for the -class, but does not provide a way to spy on calls. +If you define an ES6 class using the same filename as the mocked class in the `__mocks__` folder, it will serve as the mock. This class will be used in place of the real class. This allows you to inject a test implementation for the class, but does not provide a way to spy on calls. For the contrived example, the mock might look like this: @@ -233,16 +200,11 @@ export default class SoundPlayer { ### Simple mock using module factory parameter -The module factory function passed to `jest.mock(path, moduleFactory)` can be a -HOF that returns a function\*. This will allow calling `new` on the mock. Again, -this allows you to inject different behavior for testing, but does not provide a -way to spy on calls. +The module factory function passed to `jest.mock(path, moduleFactory)` can be a HOF that returns a function\*. This will allow calling `new` on the mock. Again, this allows you to inject different behavior for testing, but does not provide a way to spy on calls. #### \* Module factory function must return a function -In order to mock a constructor function, the module factory must return a -constructor function. In other words, the module factory must be a function that -returns a function - a higher-order function (HOF). +In order to mock a constructor function, the module factory must return a constructor function. In other words, the module factory must be a function that returns a function - a higher-order function (HOF). ```javascript jest.mock('./sound-player', () => { @@ -254,8 +216,7 @@ jest.mock('./sound-player', () => { **_Note: Arrow functions won't work_** -Note that the mock can't be an arrow function because calling `new` on an arrow -function is not allowed in JavaScript. So this won't work: +Note that the mock can't be an arrow function because calling `new` on an arrow function is not allowed in JavaScript. So this won't work: ```javascript jest.mock('./sound-player', () => { @@ -266,23 +227,15 @@ jest.mock('./sound-player', () => { }); ``` -This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, -unless the code is transpiled to ES5, e.g. by babel-preset-env. (ES5 doesn't -have arrow functions nor classes, so both will be transpiled to plain -functions.) +This will throw **_TypeError: \_soundPlayer2.default is not a constructor_**, unless the code is transpiled to ES5, e.g. by babel-preset-env. (ES5 doesn't have arrow functions nor classes, so both will be transpiled to plain functions.) ## Keeping track of usage (spying on the mock) -Injecting a test implementation is helpful, but you will probably also want to -test whether the class constructor and methods are called with the correct -parameters. +Injecting a test implementation is helpful, but you will probably also want to test whether the class constructor and methods are called with the correct parameters. ### Spying on the constructor -In order to track calls to the constructor, replace the function returned by the -HOF with a Jest mock function. Create it with -[`jest.fn()`](JestObjectAPI.md#jestfnimplementation), and then specify its -implementation with `mockImplementation()`. +In order to track calls to the constructor, replace the function returned by the HOF with a Jest mock function. Create it with [`jest.fn()`](JestObjectAPI.md#jestfnimplementation), and then specify its implementation with `mockImplementation()`. ```javascript import SoundPlayer from './sound-player'; @@ -294,22 +247,13 @@ jest.mock('./sound-player', () => { }); ``` -This will let us inspect usage of our mocked class, using -`SoundPlayer.mock.calls`: `expect(SoundPlayer).toHaveBeenCalled();` or -near-equivalent: `expect(SoundPlayer.mock.calls.length).toEqual(1);` +This will let us inspect usage of our mocked class, using `SoundPlayer.mock.calls`: `expect(SoundPlayer).toHaveBeenCalled();` or near-equivalent: `expect(SoundPlayer.mock.calls.length).toEqual(1);` ### Spying on methods of our class -Our mocked class will need to provide any member functions (`playSoundFile` in -the example) that will be called during our tests, or else we'll get an error -for calling a function that doesn't exist. But we'll probably want to also spy -on calls to those methods, to ensure that they were called with the expected -parameters. +Our mocked class will need to provide any member functions (`playSoundFile` in the example) that will be called during our tests, or else we'll get an error for calling a function that doesn't exist. But we'll probably want to also spy on calls to those methods, to ensure that they were called with the expected parameters. -A new object will be created each time the mock constructor function is called -during tests. To spy on method calls in all of these objects, we populate -`playSoundFile` with another mock function, and store a reference to that same -mock function in our test file, so it's available during tests. +A new object will be created each time the mock constructor function is called during tests. To spy on method calls in all of these objects, we populate `playSoundFile` with another mock function, and store a reference to that same mock function in our test file, so it's available during tests. ```javascript import SoundPlayer from './sound-player'; @@ -336,16 +280,11 @@ const mock = jest.fn().mockImplementation(() => { export default mock; ``` -Usage is similar to the module factory function, except that you can omit the -second argument from `jest.mock()`, and you must import the mocked method into -your test file, since it is no longer defined there. Use the original module -path for this; don't include `__mocks__`. +Usage is similar to the module factory function, except that you can omit the second argument from `jest.mock()`, and you must import the mocked method into your test file, since it is no longer defined there. Use the original module path for this; don't include `__mocks__`. ### Cleaning up between tests -To clear the record of calls to the mock constructor function and its methods, -we call [`mockClear()`](MockFunctionAPI.md#mockfnmockclear) in the -`beforeEach()` function: +To clear the record of calls to the mock constructor function and its methods, we call [`mockClear()`](MockFunctionAPI.md#mockfnmockclear) in the `beforeEach()` function: ```javascript beforeEach(() => { @@ -356,8 +295,7 @@ beforeEach(() => { ## Complete example -Here's a complete test file which uses the module factory parameter to -`jest.mock`: +Here's a complete test file which uses the module factory parameter to `jest.mock`: ```javascript // sound-player-consumer.test.js diff --git a/docs/ExpectAPI.md b/docs/ExpectAPI.md index 323119234334..df6eec902ab1 100644 --- a/docs/ExpectAPI.md +++ b/docs/ExpectAPI.md @@ -3,9 +3,7 @@ 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 @@ -17,13 +15,9 @@ validate different things. ### `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'`. -Here's how you would test that: +It's easier to understand this with an example. Let's say you have a method `bestLaCroixFlavor()` which is supposed to return the string `'grapefruit'`. Here's how you would test that: ```js test('the best flavor is grapefruit', () => { @@ -31,20 +25,13 @@ 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({ @@ -75,11 +62,7 @@ test('even and odd numbers', () => { }); ``` -`expect.extends` also supports async matchers. Async matchers return a Promise -so you will need to await the returned value. Let's use an example matcher to -illustrate the usage of them. We are going to implement a very similar matcher -than `toBeDivisibleBy`, only difference is that the divisible number is going to -be pulled from an external source. +`expect.extends` also supports async matchers. Async matchers return a Promise so you will need to await the returned value. Let's use an example matcher to illustrate the usage of them. We are going to implement a very similar matcher than `toBeDivisibleBy`, only difference is that the divisible number is going to be pulled from an external source. ```js expect.extend({ @@ -108,34 +91,23 @@ test('is divisible by external value', async () => { }); ``` -Matchers should return an object (or a Promise of an object) with two keys. -`pass` indicates whether there was a match or not, and `message` provides a -function with no arguments that returns an error message in case of failure. -Thus, when `pass` is false, `message` should return the error message for when -`expect(x).yourMatcher()` fails. And when `pass` is true, `message` should -return the error message for when `expect(x).not.yourMatcher()` fails. +Matchers should return an object (or a Promise of an object) with two keys. `pass` indicates whether there was a match or not, and `message` provides a function with no arguments that returns an error message in case of failure. Thus, when `pass` is false, `message` should return the error message for when `expect(x).yourMatcher()` fails. And when `pass` is true, `message` should return the error message for when `expect(x).not.yourMatcher()` fails. 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'); @@ -182,16 +154,11 @@ 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', () => { @@ -203,10 +170,7 @@ 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) { @@ -222,10 +186,7 @@ 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: @@ -262,13 +223,9 @@ describe('Beware of a misunderstanding! A sequence of dice rolls', () => { ### `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', () => { @@ -288,14 +245,9 @@ 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', () => { @@ -307,14 +259,11 @@ 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.not.arrayContaining(array)` -`expect.not.arrayContaining(array)` matches a received array which contains none -of the elements in the expected array. That is, the expected array **is not a -subset** of the received array. +`expect.not.arrayContaining(array)` matches a received array which contains none of the elements in the expected array. That is, the expected array **is not a subset** of the received array. It is the inverse of `expect.arrayContaining`. @@ -332,10 +281,7 @@ describe('not.arrayContaining', () => { ### `expect.not.objectContaining(object)` -`expect.not.objectContaining(object)` matches any received object that does not -recursively match the expected properties. That is, the expected object **is not -a subset** of the received object. Therefore, it matches a received object which -contains properties that are **not** in the expected object. +`expect.not.objectContaining(object)` matches any received object that does not recursively match the expected properties. That is, the expected object **is not a subset** of the received object. Therefore, it matches a received object which contains properties that are **not** in the expected object. It is the inverse of `expect.objectContaining`. @@ -351,8 +297,7 @@ describe('not.objectContaining', () => { ### `expect.not.stringContaining(string)` -`expect.not.stringContaining(string)` matches the received string that does not -contain the exact expected string. +`expect.not.stringContaining(string)` matches the received string that does not contain the exact expected string. It is the inverse of `expect.stringContaining`. @@ -368,8 +313,7 @@ describe('not.stringContaining', () => { ### `expect.not.stringMatching(string | regexp)` -`expect.not.stringMatching(string | regexp)` matches the received string that -does not match the expected regexp. +`expect.not.stringMatching(string | regexp)` matches the received string that does not match the expected regexp. It is the inverse of `expect.stringMatching`. @@ -385,17 +329,11 @@ describe('not.stringMatching', () => { ### `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', () => { @@ -412,13 +350,11 @@ test('onPress gets called with the right thing', () => { ### `expect.stringContaining(string)` -`expect.stringContaining(string)` matches the received string that contains the -exact expected string. +`expect.stringContaining(string)` matches the received string that contains the exact expected string. ### `expect.stringMatching(string | regexp)` -`expect.stringMatching(string | regexp)` matches the received string that -matches the expected regexp. +`expect.stringMatching(string | regexp)` matches the received string that matches the expected regexp. You can use it instead of a literal value: @@ -426,8 +362,7 @@ 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', () => { @@ -450,13 +385,9 @@ describe('stringMatching in arrayContaining', () => { ### `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'; @@ -465,20 +396,16 @@ 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', () => { @@ -488,11 +415,9 @@ test('the best flavor is not coconut', () => { ### `.resolves` -Use `resolves` to unwrap the value of a fulfilled promise so any other matcher -can be chained. If the promise is rejected the assertion fails. +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', () => { @@ -501,9 +426,7 @@ test('resolves to lemon', () => { }); ``` -Note that, since you are still testing promises, the test is still asynchronous. -Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by -returning the unwrapped assertion. +Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. Alternatively, you can use `async/await` in combination with `.resolves`: @@ -516,8 +439,7 @@ test('resolves to lemon', async () => { ### `.rejects` -Use `.rejects` to unwrap the reason of a rejected promise so any other matcher -can be chained. If the promise is fulfilled the assertion fails. +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'`: @@ -530,9 +452,7 @@ test('rejects to octopus', () => { }); ``` -Note that, since you are still testing promises, the test is still asynchronous. -Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by -returning the unwrapped assertion. +Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. Alternatively, you can use `async/await` in combination with `.rejects`. @@ -544,8 +464,7 @@ test('rejects to octopus', async () => { ### `.toBe(value)` -`toBe` just checks that a value is what you expect. It uses `Object.is` to check -exact equality. +`toBe` just checks that a value is what you expect. It uses `Object.is` to check exact equality. For example, this code will validate some properties of the `can` object: @@ -566,9 +485,7 @@ 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()` @@ -576,11 +493,7 @@ 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', () => { @@ -602,13 +515,9 @@ describe('drinkAll', () => { Also under the alias: `.toBeCalledTimes(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', () => { @@ -622,12 +531,9 @@ 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', () => { @@ -643,11 +549,7 @@ 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', () => { @@ -661,11 +563,7 @@ test('applying to all flavors does mango last', () => { Also under the alias: `.nthCalledWith(arg1, arg2, ...)` -If you have a mock function, you can use `.toHaveBeenNthCalledWith` to test what -arguments it was nth called with. For example, let's say you have a -`drinkEach(drink, Array)` function that applies `f` to a bunch of -flavors, and you want to ensure that when you call it, the first flavor it -operates on is `'lemon'` and the second one is `'octopus'`. You can write: +If you have a mock function, you can use `.toHaveBeenNthCalledWith` to test what arguments it was nth called with. For example, let's say you have a `drinkEach(drink, Array)` function that applies `f` to a bunch of flavors, and you want to ensure that when you call it, the first flavor it operates on is `'lemon'` and the second one is `'octopus'`. You can write: ```js test('drinkEach drinks each drink', () => { @@ -682,10 +580,7 @@ Note: the nth argument must be positive integer starting from 1. Also under the alias: `.toReturn()` -If you have a mock function, you can use `.toHaveReturned` to test that the mock -function successfully returned (i.e., did not throw an error) at least one time. -For example, let's say you have a mock `drink` that returns `true`. You can -write: +If you have a mock function, you can use `.toHaveReturned` to test that the mock function successfully returned (i.e., did not throw an error) at least one time. For example, let's say you have a mock `drink` that returns `true`. You can write: ```js test('drinks returns', () => { @@ -701,13 +596,9 @@ test('drinks returns', () => { Also under the alias: `.toReturnTimes(number)` -Use `.toHaveReturnedTimes` to ensure that a mock function returned successfully -(i.e., did not throw an error) an exact number of times. Any calls to the mock -function that throw an error are not counted toward the number of times the -function returned. +Use `.toHaveReturnedTimes` to ensure that a mock function returned successfully (i.e., did not throw an error) an exact number of times. Any calls to the mock function that throw an error are not counted toward the number of times the function returned. -For example, let's say you have a mock `drink` that returns `true`. You can -write: +For example, let's say you have a mock `drink` that returns `true`. You can write: ```js test('drink returns twice', () => { @@ -724,11 +615,9 @@ test('drink returns twice', () => { Also under the alias: `.toReturnWith(value)` -Use `.toHaveReturnedWith` to ensure that a mock function returned a specific -value. +Use `.toHaveReturnedWith` to ensure that a mock function returned a specific value. -For example, let's say you have a mock `drink` that returns the name of the -beverage that was consumed. You can write: +For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: ```js test('drink returns La Croix', () => { @@ -745,13 +634,9 @@ test('drink returns La Croix', () => { Also under the alias: `.lastReturnedWith(value)` -Use `.toHaveLastReturnedWith` to test the specific value that a mock function -last returned. If the last call to the mock function threw an error, then this -matcher will fail no matter what value you provided as the expected return -value. +Use `.toHaveLastReturnedWith` to test the specific value that a mock function last returned. If the last call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. -For example, let's say you have a mock `drink` that returns the name of the -beverage that was consumed. You can write: +For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: ```js test('drink returns La Croix (Orange) last', () => { @@ -770,13 +655,9 @@ test('drink returns La Croix (Orange) last', () => { Also under the alias: `.nthReturnedWith(nthCall, value)` -Use `.toHaveNthReturnedWith` to test the specific value that a mock function -returned for the nth call. If the nth call to the mock function threw an error, -then this matcher will fail no matter what value you provided as the expected -return value. +Use `.toHaveNthReturnedWith` to test the specific value that a mock function returned for the nth call. If the nth call to the mock function threw an error, then this matcher will fail no matter what value you provided as the expected return value. -For example, let's say you have a mock `drink` that returns the name of the -beverage that was consumed. You can write: +For example, let's say you have a mock `drink` that returns the name of the beverage that was consumed. You can write: ```js test('drink returns expected nth calls', () => { @@ -796,8 +677,7 @@ Note: the nth argument must be positive integer starting from 1. ### `.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', () => { @@ -805,12 +685,9 @@ 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', () => { @@ -818,14 +695,11 @@ 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', () => { @@ -833,14 +707,11 @@ 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(); @@ -849,9 +720,7 @@ 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', () => { @@ -860,14 +729,11 @@ 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', () => { @@ -877,9 +743,7 @@ 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', () => { @@ -889,9 +753,7 @@ 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', () => { @@ -901,9 +763,7 @@ 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', () => { @@ -913,8 +773,7 @@ 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 {} @@ -926,8 +785,7 @@ 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() { @@ -941,9 +799,7 @@ 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(); @@ -952,10 +808,7 @@ 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', () => { @@ -964,14 +817,11 @@ 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', () => { @@ -979,17 +829,13 @@ 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', () => { @@ -999,10 +845,7 @@ 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', () => { @@ -1015,10 +858,7 @@ 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 = { @@ -1040,14 +880,11 @@ 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. @@ -1061,9 +898,7 @@ 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', () => { @@ -1086,16 +921,9 @@ 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. @@ -1145,19 +973,11 @@ 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 you may -use -[dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) -or an array containing the keyPath for deep references. +Use `.toHaveProperty` to check if property at provided reference `keyPath` exists for an object. For checking deeply nested properties in an object you may use [dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) or an array containing the keyPath for deep references. -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 @@ -1203,29 +1023,22 @@ test('this house has my desired features', () => { ### `.toMatchSnapshot(propertyMatchers, snapshotName)` -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. -The optional propertyMatchers argument allows you to specify asymmetric matchers -which are verified instead of the exact values. +The optional propertyMatchers argument allows you to specify asymmetric matchers which are verified instead of the exact values. -The last argument allows you option to specify a snapshot name. Otherwise, the -name is inferred from the test. +The last argument allows you option to specify a 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._ ### `.toStrictEqual(value)` -Use `.toStrictEqual` to test that objects have the same types as well as -structure. +Use `.toStrictEqual` to test that objects have the same types as well as structure. Differences from `.toEqual`: -* Keys with `undefined` properties are checked. e.g. `{a: undefined, b: 2}` does - not match `{b: 2}` when using `.toStrictEqual`. -* Object types are checked to be equal. e.g. A class instance with fields `a` - and `b` will not equal a literal object with fields `a` and `b`. +* Keys with `undefined` properties are checked. e.g. `{a: undefined, b: 2}` does not match `{b: 2}` when using `.toStrictEqual`. +* Object types are checked to be equal. e.g. A class instance with fields `a` and `b` will not equal a literal object with fields `a` and `b`. ```js class LaCroix { @@ -1246,9 +1059,7 @@ describe('the La Croix cans on my desk', () => { 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', () => { @@ -1258,10 +1069,7 @@ 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 that should be contained in -the error message, a class for the error, or a regex that should match the error -message. 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 that should be contained in the error message, a class for the error, or a regex that should match the error message. For example, let's say that `drinkFlavor` is coded like this: ```js function drinkFlavor(flavor) { @@ -1292,15 +1100,11 @@ 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) { @@ -1329,6 +1133,4 @@ 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 a989ab243511..e658b50340f3 100644 --- a/docs/GettingStarted.md +++ b/docs/GettingStarted.md @@ -15,8 +15,7 @@ Or [`npm`](https://www.npmjs.com/): npm install --save-dev jest ``` -Let's get started by writing a test for a hypothetical function that adds two -numbers. First, create a `sum.js` file: +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) { @@ -54,51 +53,39 @@ 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 `yarn global add 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 `yarn global add 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: ```bash yarn add --dev babel-jest babel-core regenerator-runtime ``` -> Note: If you are using a babel version 7 then you need to install `babel-jest` -> with the following command: +> Note: If you are using a babel version 7 then you need to install `babel-jest` with the following command: > > ```bash > yarn add --dev babel-jest 'babel-core@^7.0.0-0' @babel/core 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-env`](https://babeljs.io/docs/plugins/preset-env/) 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-env`](https://babeljs.io/docs/plugins/preset-env/) and [`babel-preset-react`](https://babeljs.io/docs/plugins/preset-react/) presets: ```json { @@ -108,14 +95,9 @@ in your project's root folder. For example, if you are using ES6 and 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 ES6 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 ES6 modules with the option `{ "modules": false }`, you have to make sure to turn this on in your test environment. ```json { @@ -128,10 +110,7 @@ You are now set up to use all ES6 features and React specific syntax. } ``` -> 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 @@ -144,12 +123,8 @@ You are now set up to use all ES6 features and React specific syntax. ### 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 4c31a99530b3..826755904c86 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -3,8 +3,7 @@ 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 @@ -16,15 +15,11 @@ environment. You don't have to require or import anything to use them. ### `afterAll(fn, timeout)` -Runs a function after all the tests in this file have completed. If the function -returns a promise or is a generator, Jest waits for that promise to resolve -before continuing. +Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to clean up some global setup state that is -shared across tests. +This is often useful if you want to clean up some global setup state that is shared across tests. For example: @@ -52,26 +47,19 @@ 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, timeout)` -Runs a function after each one of the tests in this file completes. If the -function returns a promise or is a generator, Jest waits for that promise to -resolve before continuing. +Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to clean up some temporary state that is -created by each test. +This is often useful if you want to clean up some temporary state that is created by each test. For example: @@ -99,26 +87,19 @@ 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, timeout)` -Runs a function before any of the tests in this file run. If the function -returns a promise or is a generator, Jest waits for that promise to resolve -before running tests. +Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to set up some global state that will be used -by many tests. +This is often useful if you want to set up some global state that will be used by many tests. For example: @@ -142,28 +123,19 @@ 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, timeout)` -Runs a function before each of the tests in this file runs. If the function -returns a promise or is a generator, Jest waits for that promise to resolve -before running the test. +Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to reset some global state that will be used by -many tests. +This is often useful if you want to reset some global state that will be used by many tests. For example: @@ -193,17 +165,13 @@ 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 = { @@ -222,9 +190,7 @@ 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: @@ -258,19 +224,15 @@ describe('binaryStringToNumber', () => { ### `describe.each(table)(name, fn)` -Use `describe.each` if you keep duplicating the same test suites with different -data. `describe.each` allows you to write the test suite once and pass data in. +Use `describe.each` if you keep duplicating the same test suites with different data. `describe.each` allows you to write the test suite once and pass data in. `describe.each` is available with two APIs: #### 1. `describe.each(table)(name, fn)` -* `table`: `Array` of Arrays with the arguments that are passed into the `fn` - for each row. -* `name`: `String` the title of the test suite, use `%s` to positionally inject - test data into the suite title. -* `fn`: `Function` the suite of tests to be ran, this is the function that will - receive the parameters in each row as function arguments. +* `table`: `Array` of Arrays with the arguments that are passed into the `fn` for each row. +* `name`: `String` the title of the test suite, use `%s` to positionally inject test data into the suite title. +* `fn`: `Function` the suite of tests to be ran, this is the function that will receive the parameters in each row as function arguments. Example: @@ -297,12 +259,9 @@ describe.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( * `table`: `Tagged Template Literal` * First row of variable name column headings separated with `|` - * One or more subsequent rows of data supplied as template literal expressions - using `${value}` syntax. -* `name`: `String` the title of the test suite, use `$variable` to inject test - data into the suite title from the tagged template expressions. -* `fn`: `Function` the suite of tests to be ran, this is the function that will - receive the test data object. + * One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. +* `name`: `String` the title of the test suite, use `$variable` to inject test data into the suite title from the tagged template expressions. +* `fn`: `Function` the suite of tests to be ran, this is the function that will receive the test data object. Example: @@ -351,11 +310,9 @@ describe('my other beverage', () => { ### `describe.only.each(table)(name, fn)` -Also under the aliases: `fdescribe.each(table)(name, fn)` and -`` fdescribe.each`table`(name, fn) `` +Also under the aliases: `fdescribe.each(table)(name, fn)` and `` fdescribe.each`table`(name, fn) `` -Use `describe.only.each` if you want to only run specific tests suites of data -driven tests. +Use `describe.only.each` if you want to only run specific tests suites of data driven tests. `describe.only.each` is available with two APIs: @@ -399,8 +356,7 @@ test('will not be ran', () => { 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', () => { @@ -418,16 +374,13 @@ 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. ### `describe.skip.each(table)(name, fn)` -Also under the aliases: `xdescribe.each(table)(name, fn)` and -`` xdescribe.each`table`(name, fn) `` +Also under the aliases: `xdescribe.each(table)(name, fn)` and `` xdescribe.each`table`(name, fn) `` -Use `describe.skip.each` if you want to stop running a suite of data driven -tests. +Use `describe.skip.each` if you want to stop running a suite of data driven tests. `describe.skip.each` is available with two APIs: @@ -469,21 +422,17 @@ test('will be ran', () => { ### `require.requireActual(moduleName)` -Returns the actual module instead of a mock, bypassing all checks on whether the -module should receive a mock implementation or not. +Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. ### `require.requireMock(moduleName)` -Returns a mock module instead of the actual module, bypassing all checks on -whether the module should be required normally or not. +Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. ### `test(name, fn, timeout)` Also under the alias: `it(name, fn, timeout)` -All you need in a test file is the `test` method which runs a test. For example, -let's say there's a function `inchesOfRain()` that should be zero. Your whole -test could be: +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', () => { @@ -491,19 +440,11 @@ test('did not rain', () => { }); ``` -The first argument is the test name; the second argument is a function that -contains the expectations to test. The third argument (optional) is `timeout` -(in milliseconds) for specifying how long to wait before aborting. _Note: The -default timeout is 5 seconds._ +The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -> 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', () => { @@ -513,27 +454,21 @@ 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.each(table)(name, fn)` -Also under the alias: `it.each(table)(name, fn)` and -`` it.each`table`(name, fn) `` +Also under the alias: `it.each(table)(name, fn)` and `` it.each`table`(name, fn) `` -Use `test.each` if you keep duplicating the same test with different data. -`test.each` allows you to write the test once and pass data in. +Use `test.each` if you keep duplicating the same test with different data. `test.each` allows you to write the test once and pass data in. `test.each` is available with two APIs: #### 1. `test.each(table)(name, fn)` -* `table`: `Array` of Arrays with the arguments that are passed into the test - `fn` for each row. -* `name`: `String` the title of the test block, use `%s` to positionally inject - parameter values into the test title. -* `fn`: `Function` the test to be ran, this is the function that will receive - the parameters in each row as function arguments. +* `table`: `Array` of Arrays with the arguments that are passed into the test `fn` for each row. +* `name`: `String` the title of the test block, use `%s` to positionally inject parameter values into the test title. +* `fn`: `Function` the test to be ran, this is the function that will receive the parameters in each row as function arguments. Example: @@ -550,12 +485,9 @@ test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])( * `table`: `Tagged Template Literal` * First row of variable name column headings separated with `|` - * One or more subsequent rows of data supplied as template literal expressions - using `${value}` syntax. -* `name`: `String` the title of the test, use `$variable` to inject test data - into the test title from the tagged template expressions. -* `fn`: `Function` the test to be ran, this is the function that will receive - the test data object. + * One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax. +* `name`: `String` the title of the test, use `$variable` to inject test data into the test title from the tagged template expressions. +* `fn`: `Function` the test to be ran, this is the function that will receive the test data object. Example: @@ -574,12 +506,9 @@ test.each` Also under the aliases: `it.only(name, fn, timeout)` or `fit(name, fn, timeout)` -When you are debugging a large test file, you will often only want to run a -subset of tests. You can use `.only` to specify which tests are the only ones -you want to run in that test file. +When you are debugging a large test file, you will often only want to run a subset of tests. You can use `.only` to specify which tests are the only ones you want to run in that test file. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ For example, let's say you had these tests: @@ -593,21 +522,15 @@ test('it is not snowing', () => { }); ``` -Only the "it is raining" test will run in that test file, since it is run with -`test.only`. +Only the "it is raining" test will run in that test file, since it is run with `test.only`. -Usually you wouldn't check code using `test.only` into source control - you -would use it 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.only.each(table)(name, fn)` -Also under the aliases: `it.only.each(table)(name, fn)`, -`fit.each(table)(name, fn)`, `` it.only.each`table`(name, fn) `` and -`` fit.each`table`(name, fn) `` +Also under the aliases: `it.only.each(table)(name, fn)`, `fit.each(table)(name, fn)`, `` it.only.each`table`(name, fn) `` and `` fit.each`table`(name, fn) `` -Use `test.only.each` if you want to only run specific tests with different test -data. +Use `test.only.each` if you want to only run specific tests with different test data. `test.only.each` is available with two APIs: @@ -645,13 +568,9 @@ test('will not be ran', () => { ### `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: @@ -665,21 +584,15 @@ 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. ### `test.skip.each(table)(name, fn)` -Also under the aliases: `it.skip.each(table)(name, fn)`, -`xit.each(table)(name, fn)`, `xtest.each(table)(name, fn)`, -`` it.skip.each`table`(name, fn) ``, `` xit.each`table`(name, fn) `` and -`` xtest.each`table`(name, fn) `` +Also under the aliases: `it.skip.each(table)(name, fn)`, `xit.each(table)(name, fn)`, `xtest.each(table)(name, fn)`, `` it.skip.each`table`(name, fn) ``, `` xit.each`table`(name, fn) `` and `` xtest.each`table`(name, fn) `` -Use `test.skip.each` if you want to stop running a collection of data driven -tests. +Use `test.skip.each` if you want to stop running a collection of data driven tests. `test.skip.each` is available with two APIs: diff --git a/docs/JestCommunity.md b/docs/JestCommunity.md index 2b60966f61ab..6f29ae016961 100644 --- a/docs/JestCommunity.md +++ b/docs/JestCommunity.md @@ -3,29 +3,17 @@ title: Jest Community id: jest-community --- -The community around Jest is working hard to make the testing experience even -greater. +The community around Jest is working hard to make the testing experience even greater. -[jest-community](https://github.com/jest-community) is a new GitHub organization -for high quality Jest additions curated by Jest maintainers and collaborators. -It already features some of our favorite projects, to name a few: +[jest-community](https://github.com/jest-community) is a new GitHub organization for high quality Jest additions curated by Jest maintainers and collaborators. It already features some of our favorite projects, to name a few: * [vscode-jest](https://github.com/jest-community/vscode-jest) * [jest-extended](https://github.com/jest-community/jest-extended) * [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) * [awesome-jest](https://github.com/jest-community/awesome-jest) -Community projects under one organisation are a great way for Jest to experiment -with new ideas/techniques and approaches. Encourage contributions from the -community and publish contributions independently at a faster pace. +Community projects under one organisation are a great way for Jest to experiment with new ideas/techniques and approaches. Encourage contributions from the community and publish contributions independently at a faster pace. -The jest-community org maintains an -[awesome-jest](https://github.com/jest-community/awesome-jest) list of great -projects and resources related to Jest, this includes all projects not just the -ones in the jest-community org. +The jest-community org maintains an [awesome-jest](https://github.com/jest-community/awesome-jest) list of great projects and resources related to Jest, this includes all projects not just the ones in the jest-community org. -If you have something awesome to share, feel free to reach out to us! We'd love -to share your project on the awesome-jest list -([send a PR here](https://github.com/jest-community/awesome-jest/pulls)) or if -you would like to transfer your project to the jest-community org reachout to -one of the owners of the org. +If you have something awesome to share, feel free to reach out to us! We'd love to share your project on the awesome-jest list ([send a PR here](https://github.com/jest-community/awesome-jest/pulls)) or if you would like to transfer your project to the jest-community org reachout to one of the owners of the org. diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 2d0ee6c9487d..122084920bbc 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -3,9 +3,7 @@ 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 @@ -42,18 +40,15 @@ behavior. 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. -> See `automock` section of [configuration](Configuration.md#automock-boolean) -> for more information +> See `automock` section of [configuration](Configuration.md#automock-boolean) for more information -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). Jest configuration: @@ -85,22 +80,13 @@ test('original implementation', () => { }); ``` -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()` @@ -108,8 +94,7 @@ Enables automatic mocking in the module loader. Returns the `jest` object for chaining. -> See `automock` section of [configuration](Configuration.md#automock-boolean) -> for more information +> See `automock` section of [configuration](Configuration.md#automock-boolean) for more information Example: @@ -136,14 +121,11 @@ test('original implementation', () => { }); ``` -_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(); @@ -161,11 +143,9 @@ 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. +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. +This is useful when you want to create a [manual mock](ManualMocks.md) that extends the automatic mock's behavior. Example: @@ -192,8 +172,7 @@ test('implementation created by jest.genMockFromModule', () => { ### `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 @@ -207,8 +186,7 @@ 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', () => { @@ -220,8 +198,7 @@ const moduleName = require('../moduleName'); 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( @@ -236,35 +213,25 @@ jest.mock( ); ``` -_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 it runs 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 it runs after the test file that mocks the module. Returns the `jest` object for chaining. ### `jest.unmock(moduleName)` -Indicates that the module system should never return a mocked version of the -specified module from `require()` (e.g. that it should always return the real -module). +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). +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. +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: +One example when this is useful is when you want to mock a module differently within the same file: ```js beforeEach(() => { @@ -292,37 +259,29 @@ 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()` -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: @@ -355,28 +314,17 @@ Returns the `jest` object for chaining. ### `jest.runAllTicks()` -Exhausts the **micro**-task queue (usually interfaced in node via -`process.nextTick`). +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. +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()`). +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. +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()` @@ -388,55 +336,31 @@ Exhausts all tasks queued by `setImmediate()`. 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 time frame will be executed. -Additionally if those macro-tasks schedule new macro-tasks that would be -executed within the same time frame, those will be executed until there are no -more macro-tasks remaining in the queue, that should be run within `msToRun` -milliseconds. +When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via `setTimeout()` or `setInterval()`, and would be executed within this time frame will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue, that should be run within `msToRun` milliseconds. ### `jest.runOnlyPendingTimers()` -Executes only the macro-tasks that are currently pending (i.e., only the tasks -that have been queued by `setTimeout()` or `setInterval()` up to this point). If -any of the currently pending macro-tasks schedule new macro-tasks, those new -tasks will not be executed by this call. +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. +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. +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. +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. +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._ @@ -448,9 +372,7 @@ 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. @@ -462,14 +384,9 @@ Returns the `jest` object for chaining. ### `jest.spyOn(object, methodName)` -Creates a mock function similar to `jest.fn` but also tracks calls to -`object[methodName]`. Returns a Jest mock function. +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);`_ +_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: @@ -502,9 +419,7 @@ test('plays video', () => { ### `jest.spyOn(object, methodName, accessType?)` -Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of -`accessType` that can be either `'get'` or `'set'`, which proves to be useful -when you want to spy on a getter or a setter, respectively. +Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of `accessType` that can be either `'get'` or `'set'`, which proves to be useful when you want to spy on a getter or a setter, respectively. Example: diff --git a/docs/JestPlatform.md b/docs/JestPlatform.md index 6a1b2541d678..549e02dce31e 100644 --- a/docs/JestPlatform.md +++ b/docs/JestPlatform.md @@ -3,18 +3,14 @@ id: jest-platform title: Jest Platform --- -You can cherry pick specific features of Jest and use them as standalone -packages. Here's a list of the available packages: +You can cherry pick specific features of Jest and use them as standalone packages. Here's a list of the available packages: ## jest-changed-files -Tool for identifying modified files in a git/hg repository. Exports two -functions: +Tool for identifying modified files in a git/hg repository. Exports two functions: -* `getChangedFilesForRoots` returns a promise that resolves to an object with - the changed files and repos. -* `findRepos` returns a promise that resolves to a set of repositories contained - in the specified path. +* `getChangedFilesForRoots` returns a promise that resolves to an object with the changed files and repos. +* `findRepos` returns a promise that resolves to a set of repositories contained in the specified path. ### Example @@ -27,14 +23,11 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-changed-files/README.md). ## jest-diff -Tool for visualizing changes in data. Exports a function that compares two -values of any type and returns a "pretty-printed" string illustrating the -difference between the two arguments. +Tool for visualizing changes in data. Exports a function that compares two values of any type and returns a "pretty-printed" string illustrating the difference between the two arguments. ### Example @@ -52,8 +45,7 @@ console.log(result); ## jest-docblock -Tool for extracting and parsing the comments at the top of a JavaScript file. -Exports various function to manipulate the data inside the comment block. +Tool for extracting and parsing the comments at the top of a JavaScript file. Exports various function to manipulate the data inside the comment block. ### Example @@ -76,13 +68,11 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-docblock/README.md). ## jest-get-type -Module that identifies the primitive type of any JavaScript value. Exports a -function that returns a string with the type of the value passed as argument. +Module that identifies the primitive type of any JavaScript value. Exports a function that returns a string with the type of the value passed as argument. ### Example @@ -103,13 +93,9 @@ console.log(getType(undefinedValue)); ## jest-validate -Tool for validating configurations submitted by users. Exports a function that -takes two arguments: the user's configuration and an object containing an -example configuration and other options. The return value is an object with two -attributes: +Tool for validating configurations submitted by users. Exports a function that takes two arguments: the user's configuration and an object containing an example configuration and other options. The return value is an object with two attributes: -* `hasDeprecationWarnings`, a boolean indicating whether the submitted - configuration has deprecation warnings, +* `hasDeprecationWarnings`, a boolean indicating whether the submitted configuration has deprecation warnings, * `isValid`, a boolean indicating whether the configuration is correct or not. ### Example @@ -129,15 +115,11 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-validate/README.md). ## jest-worker -Module used for parallelization of tasks. Exports a class `Worker` that takes -the path of Node.js module and lets you call the module's exported methods as if -they where class methods, returning a promise that resolves when the specified -method finishes its execution in a forked process. +Module used for parallelization of tasks. Exports a class `Worker` that takes the path of Node.js module and lets you call the module's exported methods as if they where class methods, returning a promise that resolves when the specified method finishes its execution in a forked process. ### Example @@ -169,14 +151,11 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-worker/README.md). ## pretty-format -Exports a function that converts any JavaScript value into a human-readable -string. Supports all built-in JavaScript types out of the box and allows -extension for application-specific types via user-defined plugins. +Exports a function that converts any JavaScript value into a human-readable string. Supports all built-in JavaScript types out of the box and allows extension for application-specific types via user-defined plugins. ### Example @@ -192,5 +171,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/master/packages/pretty-format/README.md). diff --git a/docs/ManualMocks.md b/docs/ManualMocks.md index a3ce2abfe23c..1ecd41dcdf19 100644 --- a/docs/ManualMocks.md +++ b/docs/ManualMocks.md @@ -3,39 +3,21 @@ 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 used to stub out functionality with mock data. For example, instead of accessing a remote resource like a website or a database, you might want to create a manual mock that allows you to use fake data. This ensures your tests will be fast and not flaky. ### Mocking user modules -Manual mocks are defined by writing a module in a `__mocks__/` subdirectory -immediately adjacent to the module. For example, to mock a module called `user` -in the `models` directory, create a file called `user.js` and put it in the -`models/__mocks__` directory. Note that the `__mocks__` folder is -case-sensitive, so naming the directory `__MOCKS__` will break on some systems. +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. -> When we require that module in our tests, then explicitly calling -> `jest.mock('./moduleName')` is **required**. +> When we require that module in our tests, then explicitly calling `jest.mock('./moduleName')` is **required**. ### Mocking Node modules -If the module you are mocking is a Node module (e.g.: `lodash`), the mock should -be placed in the `__mocks__` directory adjacent to `node_modules` (unless you -configured [`roots`](Configuration.md#roots-array-string) to point to a folder -other than the project root) and will be **automatically** mocked. There's no -need to explicitly call `jest.mock('module_name')`. +If the module you are mocking is a Node module (e.g.: `lodash`), the mock should be placed in the `__mocks__` directory adjacent to `node_modules` (unless you configured [`roots`](Configuration.md#roots-array-string) to point to a folder other than the project root) and will be **automatically** mocked. There's no need to explicitly call `jest.mock('module_name')`. -Scoped modules can be mocked by creating a file in a directory structure that -matches the name of the scoped module. For example, to mock a scoped module -called `@scope/project-name`, create a file at -`__mocks__/@scope/project-name.js`, creating the `@scope/` directory -accordingly. +Scoped modules can be mocked by creating a file in a directory structure that matches the name of the scoped module. For example, to mock a scoped module called `@scope/project-name`, create a file at `__mocks__/@scope/project-name.js`, creating the `@scope/` directory accordingly. -> Warning: If we want to mock Node's core modules (e.g.: `fs` or `path`), then -> explicitly calling e.g. `jest.mock('path')` is **required**, because core Node -> modules are not mocked by default. +> Warning: If we want to mock Node's core modules (e.g.: `fs` or `path`), then explicitly calling e.g. `jest.mock('path')` is **required**, because core Node modules are not mocked by default. ### Examples @@ -52,20 +34,11 @@ accordingly. └── views ``` -When a manual mock exists for a given module, Jest's module system will use that -module when explicitly calling `jest.mock('moduleName')`. However, when -`automock` is set to `true`, the manual mock implementation will be used instead -of the automatically created mock, even if `jest.mock('moduleName')` is not -called. To opt out of this behavior you will need to explicitly call -`jest.unmock('moduleName')` in tests that should use the actual module -implementation. +When a manual mock exists for a given module, Jest's module system will use that module when explicitly calling `jest.mock('moduleName')`. However, when `automock` is set to `true`, the manual mock implementation will be used instead of the automatically created mock, even if `jest.mock('moduleName')` is not called. To opt out of this behavior you will need to explicitly call `jest.unmock('moduleName')` in tests that should use the actual module implementation. -> Note: In order to mock properly, Jest needs `jest.mock('moduleName')` to be in -> the same scope as the `require/import` statement. +> Note: In order to mock properly, Jest needs `jest.mock('moduleName')` to be in the same scope as the `require/import` statement. -Here's a contrived example where we have a module that provides a summary of all -the files in a given directory. In this case we use the core (built in) `fs` -module. +Here's a contrived example where we have a module that provides a summary of all the files in a given directory. In this case we use the core (built in) `fs` module. ```javascript // FileSummarizer.js @@ -83,10 +56,7 @@ 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 -automatic mock. Our manual mock will implement custom versions of the `fs` APIs -that we can build on for our tests: +Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: ```javascript // __mocks__/fs.js @@ -124,8 +94,7 @@ fs.readdirSync = readdirSync; module.exports = fs; ``` -Now we write our test. Note that we need to explicitly tell that we want to mock -the `fs` module because it’s a core Node module: +Now we write our test. Note that we need to explicitly tell that we want to mock the `fs` module because it’s a core Node module: ```javascript // __tests__/FileSummarizer-test.js @@ -155,40 +124,19 @@ 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 -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. +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. -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). +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) -then you'll normally be inclined to put your `import` statements at the top of -the test file. But often you need to instruct Jest to use a mock before modules -use it. For this reason, Jest will automatically hoist `jest.mock` calls to the -top of the module (before any imports). To learn more about this and see it in -action, see [this repo](https://github.com/kentcdodds/how-jest-mocking-works). +If you're using [ES module imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) then you'll normally be inclined to put your `import` statements at the top of the test file. But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist `jest.mock` calls to the top of the module (before any imports). To learn more about this and see it in action, see [this repo](https://github.com/kentcdodds/how-jest-mocking-works). ### Mocking methods which are not implemented in JSDOM -If some code uses a method which JSDOM (the DOM implementation used by Jest) -hasn't implemented yet, testing it is not easily possible. This is e.g. the case -with `window.matchMedia()`. Jest returns -`TypeError: window.matchMedia is not a function` and doesn't properly execute -the test. +If some code uses a method which JSDOM (the DOM implementation used by Jest) hasn't implemented yet, testing it is not easily possible. This is e.g. the case with `window.matchMedia()`. Jest returns `TypeError: window.matchMedia is not a function` and doesn't properly execute the test. In this case, mocking `matchMedia` in the test file should solve the issue: @@ -204,11 +152,7 @@ window.matchMedia = jest.fn().mockImplementation(query => { }); ``` -This works if `window.matchMedia()` is used in a function (or method) which is -invoked in the test. If `window.matchMedia()` is executed directly in the tested -file, Jest reports the same error. In this case, the solution is to move the -manual mock into a separate file and include this one in the test **before** the -tested file: +This works if `window.matchMedia()` is used in a function (or method) which is invoked in the test. If `window.matchMedia()` is executed directly in the tested file, Jest reports the same error. In this case, the solution is to move the manual mock into a separate file and include this one in the test **before** the tested file: ```js import './matchMedia.mock'; // Must be imported before the tested file diff --git a/docs/MigrationGuide.md b/docs/MigrationGuide.md index 79d7eb29041a..bb5ccaa98d79 100644 --- a/docs/MigrationGuide.md +++ b/docs/MigrationGuide.md @@ -3,32 +3,15 @@ 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), -[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). +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). Install Jest Codemods with `yarn` by running: @@ -36,12 +19,10 @@ Install Jest Codemods with `yarn` by running: yarn global add 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: ```bash 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 2fd51e5f9767..58de4698337d 100644 --- a/docs/MockFunctionAPI.md +++ b/docs/MockFunctionAPI.md @@ -3,10 +3,7 @@ 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 @@ -22,13 +19,9 @@ Returns the mock name string set by calling `mockFn.mockName(value)`. ### `mockFn.mock.calls` -An array containing the call arguments of all calls that have been made to this -mock function. Each item in the array is an array of arguments that were passed -during the call. +An array containing the call arguments of all calls that have been made to this mock function. Each item in the array is an array of arguments that were passed during the call. -For example: A mock function `f` that has been called twice, with the arguments -`f('arg1', 'arg2')`, and then with the arguments `f('arg3', 'arg4')`, would have -a `mock.calls` array that looks like this: +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']]; @@ -36,15 +29,9 @@ a `mock.calls` array that looks like this: ### `mockFn.mock.results` -An array containing the results of all calls that have been made to this mock -function. Each entry in this array is an object containing a boolean `isThrow` -property, and a `value` property. `isThrow` is true if the call terminated due -to a `throw`, or false if the the call returned normally. The `value` property -contains the value that was thrown or returned. +An array containing the results of all calls that have been made to this mock function. Each entry in this array is an object containing a boolean `isThrow` property, and a `value` property. `isThrow` is true if the call terminated due to a `throw`, or false if the the call returned normally. The `value` property contains the value that was thrown or returned. -For example: A mock function `f` that has been called three times, returning -`result1`, throwing an error, and then returning `result2`, would have a -`mock.results` array that looks like this: +For example: A mock function `f` that has been called three times, returning `result1`, throwing an error, and then returning `result2`, would have a `mock.results` array that looks like this: ```js [ @@ -67,11 +54,9 @@ For example: A mock function `f` that has been called three times, returning ### `mockFn.mock.instances` -An array that contains all the object instances that have been instantiated from -this mock function using `new`. +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: +For example: A mock function that has been instantiated twice would have the following `mock.instances` array: ```js const mockFn = jest.fn(); @@ -85,58 +70,37 @@ 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. +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. +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. +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. +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. +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()`. -The [`restoreMocks`](configuration.html#restoremocks-boolean) configuration -option is available to restore mocks automatically between tests. +The [`restoreMocks`](configuration.html#restoremocks-boolean) configuration option is available to restore mocks automatically between tests. ### `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. +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)`._ +_Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`._ For example: @@ -179,9 +143,7 @@ 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. ```js const myMockFn = jest @@ -194,10 +156,7 @@ myMockFn((err, val) => console.log(val)); // true myMockFn((err, val) => console.log(val)); // false ``` -When the mocked function runs out of implementations defined with -mockImplementationOnce, it will execute the default implementation set with -`jest.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if -they were called: +When the mocked function runs out of implementations defined with mockImplementationOnce, it will execute the default implementation set with `jest.fn(() => defaultValue)` or `.mockImplementation(() => defaultValue)` if they were called: ```js const myMockFn = jest @@ -211,8 +170,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); ### `mockFn.mockName(value)` -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: @@ -254,10 +212,7 @@ 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`. ```js const myMockFn = jest diff --git a/docs/MockFunctions.md b/docs/MockFunctions.md index 177da5cbee82..8c40eff95369 100644 --- a/docs/MockFunctions.md +++ b/docs/MockFunctions.md @@ -3,20 +3,13 @@ id: mock-functions title: Mock Functions --- -Mock functions make it easy to test the links between code by erasing the actual -implementation of a function, capturing calls to the function (and the -parameters passed in those calls), capturing instances of constructor functions -when instantiated with `new`, and allowing test-time configuration of return -values. +Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with `new`, and allowing test-time configuration of return values. -There are two ways to mock functions: Either by creating a mock function to use -in test code, or writing a [`manual mock`](ManualMocks.md) to override a module -dependency. +There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a [`manual mock`](ManualMocks.md) to override a module dependency. ## Using a mock function -Let's imagine we're testing an implementation of a function `forEach`, which -invokes a callback for each item in a supplied array. +Let's imagine we're testing an implementation of a function `forEach`, which invokes a callback for each item in a supplied array. ```javascript function forEach(items, callback) { @@ -26,8 +19,7 @@ function forEach(items, callback) { } ``` -To test this function, we can use a mock function, and inspect the mock's state -to ensure the callback is invoked as expected. +To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected. ```javascript const mockCallback = jest.fn(); @@ -48,10 +40,7 @@ expect(mockCallback.mock.returnValues[0]).toBe(42); ## `.mock` property -All mock functions have this special `.mock` property, which is where data about -how the function has been called and what the function returned is kept. The -`.mock` property also tracks the value of `this` for each call, so it is -possible to inspect this as well: +All mock functions have this special `.mock` property, which is where data about how the function has been called and what the function returned is kept. The `.mock` property also tracks the value of `this` for each call, so it is possible to inspect this as well: ```javascript const myMock = jest.fn(); @@ -65,8 +54,7 @@ console.log(myMock.mock.instances); // > [ , ] ``` -These mock members are very useful in tests to assert how these functions get -called, instantiated, or what they returned: +These mock members are very useful in tests to assert how these functions get called, instantiated, or what they returned: ```javascript // The function was called exactly once @@ -91,8 +79,7 @@ expect(someMockFunction.mock.instances[0].name).toEqual('test'); ## Mock Return Values -Mock functions can also be used to inject test values into your code during a -test: +Mock functions can also be used to inject test values into your code during a test: ```javascript const myMock = jest.fn(); @@ -108,11 +95,7 @@ console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true ``` -Mock functions are also very effective in code that uses a functional -continuation-passing style. Code written in this style helps avoid the need for -complicated stubs that recreate behavior of the real component they're standing -in for, in favor of injecting values directly into the test right before they're -used. +Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. ```javascript const filterTestFn = jest.fn(); @@ -129,16 +112,11 @@ console.log(filterTestFn.mock.calls); // > [ [11], [12] ] ``` -Most real-world examples actually involve getting ahold of a mock function on a -dependent component and configuring that, but the technique is the same. In -these cases, try to avoid the temptation to implement logic inside of any -function that's not directly being tested. +Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. ## Mocking Modules -Suppose we have a class that fetches users from our API. The class uses -[axios](https://github.com/axios/axios) to call the API then returns the `data` -attribute which contains all the users: +Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: ```js // users.js @@ -153,13 +131,9 @@ class Users { export default Users; ``` -Now, in order to test this method without actually hitting the API (and thus -creating slow and fragile tests), we can use the `jest.mock(...)` function to -automatically mock the axios module. +Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the `jest.mock(...)` function to automatically mock the axios module. -Once we mock the module we can provide a `mockReturnValue` for `.get` that -returns the data we want our test to assert against. In effect, we are saying -that we want axios.get('/users.json') to return a fake response. +Once we mock the module we can provide a `mockReturnValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want axios.get('/users.json') to return a fake response. ```js // users.test.js @@ -181,10 +155,7 @@ test('should fetch users', () => { ## Mock Implementations -Still, there are cases where it's useful to go beyond the ability to specify -return values and full-on replace the implementation of a mock function. This -can be done with `jest.fn` or the `mockImplementationOnce` method on mock -functions. +Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. ```javascript const myMockFn = jest.fn(cb => cb(null, true)); @@ -196,8 +167,7 @@ myMockFn((err, val) => console.log(val)); // > true ``` -The `mockImplementation` method is useful when you need to define the default -implementation of a mock function that is created from another module: +The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: ```js // foo.js @@ -215,9 +185,7 @@ 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: +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 @@ -232,9 +200,7 @@ myMockFn((err, val) => console.log(val)); // > false ``` -When the mocked function runs out of implementations defined with -`mockImplementationOnce`, it will execute the default implementation set with -`jest.fn` (if it is defined): +When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): ```javascript const myMockFn = jest @@ -246,9 +212,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); // > 'first call', 'second call', 'default', 'default' ``` -For cases where we have methods that are typically chained (and thus always need -to return `this`), we have a sugary API to simplify this in the form of a -`.mockReturnThis()` function that also sits on all mocks: +For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: ```javascript const myObj = { @@ -266,10 +230,7 @@ const otherObj = { ## Mock Names -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 @@ -281,8 +242,7 @@ const myMockFn = jest ## Custom Matchers -Finally, in order to make it simpler to assert how mock functions have been -called, we've added some custom matcher functions for you: +Finally, in order to make it simpler to assert how mock functions have been called, we've added some custom matcher functions for you: ```javascript // The mock function was called at least once @@ -298,9 +258,7 @@ expect(mockFunc).lastCalledWith(arg1, arg2); expect(mockFunc).toMatchSnapshot(); ``` -These matchers are really just sugar for common forms of inspecting the `.mock` -property. You can always do this manually yourself if that's more to your taste -or if you need to do something more specific: +These matchers are really just sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: ```javascript // The mock function was called at least once diff --git a/docs/MongoDB.md b/docs/MongoDB.md index c5ea6f76abe4..60addd061b53 100644 --- a/docs/MongoDB.md +++ b/docs/MongoDB.md @@ -3,9 +3,7 @@ id: mongodb title: Using with MongoDB --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [MongoDB](https://www.mongodb.com/). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). ## A jest-mongodb example @@ -125,5 +123,4 @@ it('should aggregate docs from collection', async () => { }); ``` -Here's the code of -[full working example](https://github.com/vladgolubev/jest-mongodb). +Here's the code of [full working example](https://github.com/vladgolubev/jest-mongodb). diff --git a/docs/MoreResources.md b/docs/MoreResources.md index 096dd946e34d..e2c2aeb318e0 100644 --- a/docs/MoreResources.md +++ b/docs/MoreResources.md @@ -3,36 +3,22 @@ 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 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/packages/react/src/__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/packages/react/src/__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://discord.gg/MWRhKCj) 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://discord.gg/MWRhKCj) 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/Puppeteer.md b/docs/Puppeteer.md index 7961476073b2..7ade2241cae3 100644 --- a/docs/Puppeteer.md +++ b/docs/Puppeteer.md @@ -3,14 +3,11 @@ id: puppeteer title: Using with puppeteer --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). ## Use Puppeteer Preset -[Jest Puppeteer](https://github.com/smooth-code/jest-puppeteer) provides all -required configuration to run your tests using Puppeteer. +[Jest Puppeteer](https://github.com/smooth-code/jest-puppeteer) provides all required configuration to run your tests using Puppeteer. 1. First install `jest-puppeteer` @@ -119,5 +116,4 @@ describe( ); ``` -Here's the code of -[full working example](https://github.com/xfumihiro/jest-puppeteer-example). +Here's the code of [full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/docs/SetupAndTeardown.md b/docs/SetupAndTeardown.md index c5d34e9f75a4..e5a43e0fcf52 100644 --- a/docs/SetupAndTeardown.md +++ b/docs/SetupAndTeardown.md @@ -3,19 +3,13 @@ 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(() => { @@ -35,11 +29,7 @@ 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(() => { @@ -49,13 +39,9 @@ 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(() => { @@ -77,13 +63,9 @@ 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 @@ -115,9 +97,7 @@ describe('matching cities to foods', () => { }); ``` -Note that the top-level `beforeEach` is executed before the `beforeEach` inside -the `describe` block. It may help to illustrate the order of execution of all -hooks. +Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. ```js beforeAll(() => console.log('1 - beforeAll')); @@ -149,12 +129,7 @@ describe('Scoped / Nested block', () => { ### Order of execution of describe and test blocks -Jest executes all describe handlers in a test file _before_ it executes any of -the actual tests. This is another reason to do setup and teardown in `before*` -and `after*` handlers rather in the describe blocks. Once the describe blocks -are complete, by default Jest runs all the tests serially in the order they were -encountered in the collection phase, waiting for each to finish and be tidied up -before moving on. +Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown in `before*` and `after*` handlers rather in the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on. Consider the following illustrative test file and output: @@ -200,9 +175,7 @@ describe('outer', () => { ### 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', () => { @@ -214,8 +187,4 @@ 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 dc22eea4cb44..34604df86e23 100644 --- a/docs/SnapshotTesting.md +++ b/docs/SnapshotTesting.md @@ -3,23 +3,13 @@ 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'; @@ -34,9 +24,7 @@ it('renders correctly', () => { }); ``` -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`] = ` @@ -51,34 +39,15 @@ 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 @@ -94,32 +63,19 @@ 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: ```bash jest --updateSnapshot ``` -Go ahead and accept the changes by running the above command. You may also use -the equivalent single-character `-u` flag to re-generate snapshots if you -prefer. This will re-generate snapshot artifacts for all failing snapshot tests. -If we had any additional failing snapshot tests due to an unintentional bug, we -would need to fix the bug before re-generating snapshots to avoid recording -snapshots of the buggy behavior. +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. ### Interactive Snapshot Mode @@ -127,24 +83,19 @@ Failed snapshots can also be updated interactively in watch mode: ![](/jest/img/content/interactiveSnapshot.png) -Once you enter Interactive Snapshot Mode, Jest will step you through the failed -snapshots one test at a time and give you the opportunity to review the failed -output. +Once you enter Interactive Snapshot Mode, Jest will step you through the failed snapshots one test at a time and give you the opportunity to review the failed output. From here you can choose to update that snapshot or skip to the next: ![](/jest/img/content/interactiveSnapshotUpdate.gif) -Once you're finished, Jest will give you a summary before returning back to -watch mode: +Once you're finished, Jest will give you a summary before returning back to watch mode: ![](/jest/img/content/interactiveSnapshotDone.png) ### Property Matchers -Often there are fields in the object you want to snapshot which are generated -(like IDs and Dates). If you try to snapshot these objects, they will force the -snapshot to fail on every run: +Often there are fields in the object you want to snapshot which are generated (like IDs and Dates). If you try to snapshot these objects, they will force the snapshot to fail on every run: ```javascript it('will fail every time', () => { @@ -167,9 +118,7 @@ Object { `; ``` -For these cases, Jest allows providing an asymmetric matcher for any property. -These matchers are checked before the snapshot is written or tested, and then -saved to the snapshot file instead of the received value: +For these cases, Jest allows providing an asymmetric matcher for any property. These matchers are checked before the snapshot is written or tested, and then saved to the snapshot file instead of the received value: ```javascript it('will check the matchers and pass', () => { @@ -197,64 +146,33 @@ Object { ## Best Practices -Snapshots are a fantastic tool for identifying unexpected interface changes -within your application – whether that interface is an API response, UI, logs, -or error messages. As with any testing strategy, there are some best-practices -you should be aware of, and guidelines you should follow, in order to use them -effectively. +Snapshots are a fantastic tool for identifying unexpected interface changes within your application – whether that interface is an API response, UI, logs, or error messages. As with any testing strategy, there are some best-practices you should be aware of, and guidelines you should follow, in order to use them effectively. ### 1. Treat snapshots as code -Commit snapshots and review them as part of your regular code review process. -This means treating snapshots as you would any other type of test or code in -your project. +Commit snapshots and review them as part of your regular code review process. This means treating snapshots as you would any other type of test or code in your project. -Ensure that your snapshots are readable by keeping them focused, short, and by -using tools that enforce these stylistic conventions. +Ensure that your snapshots are readable by keeping them focused, short, and by using tools that enforce these stylistic conventions. -As mentioned previously, Jest uses -[`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make -snapshots human-readable, but you may find it useful to introduce additional -tools, like -[`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with -its -[`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-large-snapshots.md) -option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with -its component snapshot comparison feature, to promote committing short, focused -assertions. +As mentioned previously, Jest uses [`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make snapshots human-readable, but you may find it useful to introduce additional tools, like [`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with its [`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-large-snapshots.md) option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with its component snapshot comparison feature, to promote committing short, focused assertions. -The goal is to make it easy to review snapshots in pull requests, and fight -against the habit of simply regenerating snapshots when test suites fail instead -of examining the root causes of their failure. +The goal is to make it easy to review snapshots in pull requests, and fight against the habit of simply regenerating snapshots when test suites fail instead of examining the root causes of their failure. ### 2. Tests should be deterministic -Your tests should be deterministic. Running the same tests multiple times on a -component that has not changed should produce the same results every time. -You're responsible for making sure your generated snapshots do not include -platform specific or other non-deterministic data. +Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a -[Clock](https://github.com/facebook/jest/blob/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: ```js Date.now = jest.fn(() => 1482363367071); ``` -Now, every time the snapshot test case runs, `Date.now()` will return -`1482363367071` consistently. This will result in the same snapshot being -generated for this component regardless of when the test is run. +Now, every time the snapshot test case runs, `Date.now()` will return `1482363367071` consistently. This will result in the same snapshot being generated for this component regardless of when the test is run. ### 3. Use descriptive snapshot names -Always strive to use descriptive test and/or snapshot names for snapshots. The -best names describe the expected snapshot content. This makes it easier for -reviewers to verify the snapshots during review, and for anyone to know whether -or not an outdated snapshot is the correct behavior before updating. +Always strive to use descriptive test and/or snapshot names for snapshots. The best names describe the expected snapshot content. This makes it easier for reviewers to verify the snapshots during review, and for anyone to know whether or not an outdated snapshot is the correct behavior before updating. For example, compare: @@ -280,8 +198,7 @@ exports[` should render Alan Turing`] = ` `; ``` -Since the later describes exactly what's expected in the output, it's easy to -see when it's wrong: +Since the later describes exactly what's expected in the output, it's easy to see when it's wrong: ```js exports[` should render null`] = ` @@ -297,74 +214,35 @@ exports[` should render Alan Turing`] = `null`; ### Are snapshots written automatically on Continuous Integration (CI) systems? -No, as of Jest 20, snapshots in Jest are not automatically written when Jest is -run in a CI system without explicitly passing `--updateSnapshot`. It is expected -that all snapshots are part of the code that is run on CI and since new -snapshots automatically pass, they should not pass a test run on a CI system. It -is recommended to always commit all snapshots and to keep them in version -control. +No, as of Jest 20, snapshots in Jest are not automatically written when Jest is run in a CI system without explicitly passing `--updateSnapshot`. It is expected that all snapshots are part of the code that is run on CI and since new snapshots automatically pass, they should not pass a test run on a CI system. It is recommended to always commit all snapshots and to keep them in version control. ### Should snapshot files be committed? -Yes, all snapshot files should be committed alongside the modules they are -covering and their tests. They should be considered 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](TutorialReact.md) and [React Native](TutorialReactNative.md) components -are a good use case for snapshot testing. However, snapshots can capture any -serializable value and should be used anytime the goal is testing whether the -output is correct. The Jest repository contains many examples of testing the -output of Jest itself, the output of Jest's assertion library as well as log -messages from various parts of the Jest codebase. See an example of -[snapshotting CLI output](https://github.com/facebook/jest/blob/master/integration-tests/__tests__/console.test.js) -in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/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 2a9e89b8b78a..cf6a9e560476 100644 --- a/docs/TestingAsyncCode.md +++ b/docs/TestingAsyncCode.md @@ -3,21 +3,15 @@ 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! @@ -30,12 +24,9 @@ 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 => { @@ -48,18 +39,13 @@ 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', () => { @@ -70,12 +56,9 @@ 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', () => { @@ -86,9 +69,7 @@ test('the fetch fails with an error', () => { ### `.resolves` / `.rejects` -You can also use the `.resolves` matcher in your expect statement, and Jest will -wait for that promise to resolve. If the promise is rejected, the test will -automatically fail. +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', () => { @@ -97,12 +78,9 @@ 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', () => { @@ -113,9 +91,7 @@ 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 () => { @@ -148,9 +124,6 @@ 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 3010dff8c6ca..d6b13ec70a13 100644 --- a/docs/TestingFrameworks.md +++ b/docs/TestingFrameworks.md @@ -3,34 +3,25 @@ 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 diff --git a/docs/TimerMocks.md b/docs/TimerMocks.md index 40754118e4f5..d23dbe20a22e 100644 --- a/docs/TimerMocks.md +++ b/docs/TimerMocks.md @@ -3,11 +3,7 @@ id: timer-mocks title: Timer Mocks --- -The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, -`clearInterval`) are less than ideal for a testing environment since they depend -on real time to elapse. Jest can swap out timers with functions that allow you -to control the passage of time. -[Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) +The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) ```javascript // timerGame.js @@ -39,17 +35,11 @@ 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. If running multiple -tests inside of one file or describe block, `jest.useFakeTimers();` can be -called before each test manually or with a setup function such as `beforeEach`. -Not doing so will result in the internal usage counter not being reset. +Here we enable fake timers by calling `jest.useFakeTimers();`. This mocks out setTimeout and other timer functions with mock functions. If running multiple tests inside of one file or describe block, `jest.useFakeTimers();` can be called before each test manually or with a setup function such as `beforeEach`. Not doing so will result in the internal usage counter not being reset. ## Run All Timers -Another test we might want to write for this module is one that asserts that the -callback is called after 1 second. To do this, we're going to use Jest's timer -control APIs to fast-forward time right in the middle of the test: +Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test: ```javascript test('calls the callback after 1 second', () => { @@ -72,10 +62,7 @@ test('calls the callback after 1 second', () => { ## Run Pending Timers -There are also scenarios where you might have a recursive timer -- that is a -timer that sets a new timer in its own callback. For these, running all the -timers would be an endless loop… so something like `jest.runAllTimers()` is not -desirable. For these cases you might use `jest.runOnlyPendingTimers()`: +There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: ```javascript // infiniteTimerGame.js @@ -135,13 +122,7 @@ describe('infiniteTimerGame', () => { ##### renamed from `runTimersToTime` to `advanceTimersByTime` in Jest **22.0.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 time frame, will be executed. Additionally if those -macro-tasks schedule new macro-tasks that would be executed within the same time -frame, those will be executed until there are no more macro-tasks remaining in -the queue that should be run within msToRun milliseconds. +Another possibility is use `jest.advanceTimersByTime(msToRun)`. When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue that should be run within msToRun milliseconds. ```javascript // timerGame.js @@ -177,8 +158,6 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { }); ``` -Lastly, it may occasionally be useful in some tests to be able to clear all of -the pending timers. For this, we have `jest.clearAllTimers()`. +Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at -[examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). +The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). diff --git a/docs/Troubleshooting.md b/docs/Troubleshooting.md index 95f3fb5c3978..f17ea40c727e 100644 --- a/docs/Troubleshooting.md +++ b/docs/Troubleshooting.md @@ -7,11 +7,9 @@ Uh oh, something went wrong? Use this guide to resolve issues with Jest. ### Tests are Failing and You Don't Know Why -Try using the debugging support built into Node. Note: This will only work in -Node.js 8+. +Try using the debugging support built into Node. Note: This will only work in Node.js 8+. -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: ```bash node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] @@ -19,34 +17,17 @@ 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: @@ -72,8 +53,7 @@ Then attach VS Code's debugger using the following `launch.json` config: } ``` -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 { @@ -117,9 +97,7 @@ or the following for Windows: } ``` -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 { @@ -140,35 +118,21 @@ can debug your Jest tests with the following configuration: } ``` -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. +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. +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? +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 @@ -178,13 +142,9 @@ If a promise doesn't resolve at all, this error might be thrown: - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` ``` -Most commonly this is being caused by conflicting Promise implementations. -Consider replacing the global promise implementation with your own, for example -`global.Promise = require.requireActual('promise');` and/or consolidate the used -Promise libraries to a single one. +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. -If your test is long running, you may want to consider to increase the timeout -by calling `jest.setTimeout` +If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` ```js jest.setTimeout(10000); // 10 second timeout @@ -192,26 +152,17 @@ 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) -[discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/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 @@ -221,10 +172,7 @@ jest --runInBand yarn test --runInBand ``` -Another alternative to expediting test execution time on Continuous Integration -Servers such as Travis-CI is to set the max worker pool to ~_4_. Specifically on -Travis-CI, this can reduce test execution time in half. Note: The Travis CI -_free_ plan available for open source projects only includes 2 CPU cores. +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 @@ -236,22 +184,11 @@ yarn test --maxWorkers=4 ### Compatibility issues -Jest takes advantage of new features added to Node 6. We recommend that you -upgrade to the latest stable release of Node. The minimum supported version is -`v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported because the `jsdom` -version used in Jest doesn't support Node 4. However, if you need to run Jest on -Node 4, you can use the `testEnvironment` config to use a -[custom environment](https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string) -that supports Node 4, such as -[`jest-environment-node`](https://yarnpkg.com/en/package/jest-environment-node). +Jest takes advantage of new features added to Node 6. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is `v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported because the `jsdom` version used in Jest doesn't support Node 4. However, if you need to run Jest on Node 4, you can use the `testEnvironment` config to use a [custom environment](https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string) that supports Node 4, such as [`jest-environment-node`](https://yarnpkg.com/en/package/jest-environment-node). ### `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 fc25c724db07..064c42e2ffc7 100644 --- a/docs/TutorialAsync.md +++ b/docs/TutorialAsync.md @@ -3,11 +3,9 @@ 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 @@ -18,11 +16,9 @@ export function getUserName(userID) { } ``` -In the above implementation we expect the `request.js` module to return a -promise. We chain a call to `then` to receive the user name. +In the above implementation we expect the `request.js` module to return a promise. We chain a call to `then` to receive the user name. -Now imagine an implementation of `request.js` that goes to the network and -fetches some user data: +Now imagine an implementation of `request.js` that goes to the network and fetches some user data: ```js // request.js @@ -42,9 +38,7 @@ export default function request(url) { } ``` -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 @@ -83,16 +77,11 @@ 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` -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', () => { @@ -103,8 +92,7 @@ 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. @@ -121,15 +109,11 @@ 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. +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. ### 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. @@ -157,8 +141,7 @@ it('tests error with async/await', async () => { ### `.rejects` -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`. @@ -178,8 +161,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at -[examples/async](https://github.com/facebook/jest/tree/master/examples/async). +The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/master/examples/async). -If you'd like to test timers, like `setTimeout`, take a look at the -[Timer mocks](TimerMocks.md) documentation. +If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/docs/TutorialReact.md b/docs/TutorialReact.md index 9e5dcc6705ff..fdd11ccb30d1 100644 --- a/docs/TutorialReact.md +++ b/docs/TutorialReact.md @@ -3,18 +3,13 @@ id: tutorial-react title: Testing React Apps --- -At Facebook, we use Jest to test [React](http://facebook.github.io/react/) -applications. +At Facebook, we use Jest to test [React](http://facebook.github.io/react/) applications. ## Setup ### 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 will only need to add `react-test-renderer` for rendering snapshots. +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 will only need to add `react-test-renderer` for rendering snapshots. Run @@ -24,10 +19,7 @@ yarn add --dev react-test-renderer ### Setup without Create React App -If you have an existing application you'll need to install a few packages to -make everything work well together. We are using the `babel-jest` package and -the `react` babel preset to transform our code inside of the test environment. -Also see [using babel](GettingStarted.md#using-babel). +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 @@ -35,9 +27,7 @@ Run yarn add --dev jest babel-jest babel-preset-env babel-preset-react react-test-renderer ``` -Your `package.json` should look something like this (where `` -is the actual latest version number for the package). Please add the scripts and -jest configuration entries: +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 @@ -68,8 +58,7 @@ jest configuration entries: ### 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 @@ -115,8 +104,7 @@ export default class Link extends React.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 // Link.react.test.js @@ -180,19 +168,13 @@ 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). +The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/master/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 -There's a caveat around snapshot testing when using Enzyme and React 16+. If you -mock out a module using the following style: +There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style: ```js jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent'); @@ -207,34 +189,23 @@ Warning: is using uppercase HTML. Always use lowercase HTML ta Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. ``` -React 16 triggers these warnings due to how it checks element types, and the -mocked module fails these checks. Your options are: +React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are: -1. Render as text. This way you won't see the props passed to the mock - component in the snapshot, but it's straightforward: +1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward: ```js jest.mock('./SomeComponent', () => () => 'SomeComponent'); ``` -2. Render as a custom element. DOM "custom elements" aren't checked for - anything and shouldn't fire warnings. They are lowercase and have a dash in - the name. +2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name. ```js jest.mock('./Widget', () => 'mock-widget'); ``` -3. Use `react-test-renderer`. The test renderer doesn't care about element - types and will happily accept e.g. `SomeComponent`. You could check - snapshots using the test renderer, and check component behavior separately - using Enzyme. +3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme. ### 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 `yarn add --dev enzyme` to use Enzyme. If you are using a React -version below 15.5.0, you will also need to install `react-addons-test-utils`. +You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React version below 15.5.0, you will also need to install `react-addons-test-utils`. Let's implement a simple checkbox which swaps between two labels: @@ -272,9 +243,7 @@ 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 @@ -295,13 +264,11 @@ test('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at -[examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). +The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). ### 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 @@ -323,14 +290,11 @@ 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 6a1374ed4693..314a4d292b30 100644 --- a/docs/TutorialReactNative.md +++ b/docs/TutorialReactNative.md @@ -3,20 +3,13 @@ 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 @@ -28,16 +21,13 @@ automatically added to your package.json file: } ``` -_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 `yarn 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 @@ -77,8 +67,7 @@ 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 @@ -131,40 +120,23 @@ 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). +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": [ @@ -174,17 +146,11 @@ react-native: ### 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": { @@ -196,26 +162,17 @@ configuration option can help: ### 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 `
@@ -65,155 +25,84 @@ learners, and developers. They are also ## Community Update -We feel incredibly humbled that 100+ companies -[have adopted Jest](https://twitter.com/cpojer/status/803965499407290369) in the -last six months. Companies like Twitter, Pinterest, Paypal, nytimes, IBM -(Watson), Spotify, eBay, SoundCloud, Intuit, FormidableLabs, Automattic, Trivago -and Microsoft have either fully or partially switched to Jest for their -JavaScript testing needs. Thank you very much for giving this project a chance. -We would also like to thank everyone who went to conferences and meetups to -speak about Jest and to everyone who is writing blog posts about how Jest is or -isn't working for them! +We feel incredibly humbled that 100+ companies [have adopted Jest](https://twitter.com/cpojer/status/803965499407290369) in the last six months. Companies like Twitter, Pinterest, Paypal, nytimes, IBM (Watson), Spotify, eBay, SoundCloud, Intuit, FormidableLabs, Automattic, Trivago and Microsoft have either fully or partially switched to Jest for their JavaScript testing needs. Thank you very much for giving this project a chance. We would also like to thank everyone who went to conferences and meetups to speak about Jest and to everyone who is writing blog posts about how Jest is or isn't working for them! Here is what happened in the community in the last two months: -* Jason Bonta and Dmitrii Abramov - [redefined the “testing pyramid”](https://twitter.com/abramov_dmitrii/status/805913874704674816) - we were talking a lot about at Facebook. -* [jest-codemods](https://github.com/skovhus/jest-codemods#jest-codemods) now - allows you to painlessly migrate from Mocha, Tape and Ava to Jest. -* The React team announced - [improvements to the react-test-renderer](https://facebook.github.io/react/blog/2016/11/16/react-v15.4.0.html) - in 15.4.0. -* Orta Therox build an amazing - [vscode-jest integration](https://github.com/orta/vscode-jest#the-aim) and - donated the code for editor support to Jest. -* Pavithra Kodmad is documenting - [Flipkarts adoption of Jest](http://pksjce.github.io/2016/12/08/notes-on-jest) - and shares some getting started tips. -* Kent C. Dodds wrote about - [migrating to Jest at Paypal](https://medium.com/@kentcdodds/migrating-to-jest-881f75366e7e#.ticf0wchu) - and Jason Brown - [wrote about migrating to Jest as well](http://browniefed.com/blog/migrating-ava-to-jest/). -* Ben McCormick wrote about - [saving time with Jest](http://benmccormick.org/2016/12/10/saving-time-with-jest/). -* Eric Clemmons wrote about - [snapshots and storybook integration](https://medium.com/@ericclemmons/jest-snapshots-for-storybook-5bf36b5e5a3a). -* Edvin Erikson wrote about - [getting Tap output in Jest](https://medium.com/@edvinerikson/getting-jest-output-in-tap-format-6e07dc2c484c#.1l4edixhl). -* [jest-html](https://github.com/guigrpa/jest-html#jest-html--) can bring - snapshot diffing to your browser. -* There were a few - [great conversations on hackernews](https://news.ycombinator.com/item?id=13128146) - about Jest. -* The community started a great discussion about the - [future of enzyme](https://github.com/airbnb/enzyme/issues/715). -* Ruben Oostinga wrote about - [combining chai and Jest matchers](https://medium.com/@RubenOostinga/combining-chai-and-jest-matchers-d12d1ffd0303#.87si0ra2h). -* Emil Ong wrote about why - [“TDD'ing your frontend seems pointless”](https://engineering.haus.com/why-tdding-your-frontend-feels-pointless-5f710fea7325#.pql79knnm). -* Nate Hunzaker wrote about - [end-to-end testing with Jest and Nightmare](https://www.viget.com/articles/acceptance-testing-react-apps-with-jest-and-nightmare). -* [Using Jest with Angular just works](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251#.h9badqevy) - according to Matthieu Lux. -* A fantastic conversation about the - [purpose of snapshot testing](https://github.com/facebook/jest/issues/2197) is - happening right now. -* Dmitrii made a new - [music video with his metal band](https://twitter.com/abramov_dmitrii/status/806613542447157248). -* [lazyspec](https://yarnpkg.com/en/package/lazyspec) can help you create smoke - tests quickly if you are introducing tests to an existing codebase. -* Patrick Stapfer did a lightning talk about - [vim and Jest](https://twitter.com/ryyppy/status/803871975995277312). -* Mark Dalgleish was - [commenting on the value of snapshot testing](https://twitter.com/markdalgleish/status/806608159527747584). +* Jason Bonta and Dmitrii Abramov [redefined the “testing pyramid”](https://twitter.com/abramov_dmitrii/status/805913874704674816) we were talking a lot about at Facebook. +* [jest-codemods](https://github.com/skovhus/jest-codemods#jest-codemods) now allows you to painlessly migrate from Mocha, Tape and Ava to Jest. +* The React team announced [improvements to the react-test-renderer](https://facebook.github.io/react/blog/2016/11/16/react-v15.4.0.html) in 15.4.0. +* Orta Therox build an amazing [vscode-jest integration](https://github.com/orta/vscode-jest#the-aim) and donated the code for editor support to Jest. +* Pavithra Kodmad is documenting [Flipkarts adoption of Jest](http://pksjce.github.io/2016/12/08/notes-on-jest) and shares some getting started tips. +* Kent C. Dodds wrote about [migrating to Jest at Paypal](https://medium.com/@kentcdodds/migrating-to-jest-881f75366e7e#.ticf0wchu) and Jason Brown [wrote about migrating to Jest as well](http://browniefed.com/blog/migrating-ava-to-jest/). +* Ben McCormick wrote about [saving time with Jest](http://benmccormick.org/2016/12/10/saving-time-with-jest/). +* Eric Clemmons wrote about [snapshots and storybook integration](https://medium.com/@ericclemmons/jest-snapshots-for-storybook-5bf36b5e5a3a). +* Edvin Erikson wrote about [getting Tap output in Jest](https://medium.com/@edvinerikson/getting-jest-output-in-tap-format-6e07dc2c484c#.1l4edixhl). +* [jest-html](https://github.com/guigrpa/jest-html#jest-html--) can bring snapshot diffing to your browser. +* There were a few [great conversations on hackernews](https://news.ycombinator.com/item?id=13128146) about Jest. +* The community started a great discussion about the [future of enzyme](https://github.com/airbnb/enzyme/issues/715). +* Ruben Oostinga wrote about [combining chai and Jest matchers](https://medium.com/@RubenOostinga/combining-chai-and-jest-matchers-d12d1ffd0303#.87si0ra2h). +* Emil Ong wrote about why [“TDD'ing your frontend seems pointless”](https://engineering.haus.com/why-tdding-your-frontend-feels-pointless-5f710fea7325#.pql79knnm). +* Nate Hunzaker wrote about [end-to-end testing with Jest and Nightmare](https://www.viget.com/articles/acceptance-testing-react-apps-with-jest-and-nightmare). +* [Using Jest with Angular just works](https://medium.com/aya-experience/testing-an-angularjs-app-with-jest-3029a613251#.h9badqevy) according to Matthieu Lux. +* A fantastic conversation about the [purpose of snapshot testing](https://github.com/facebook/jest/issues/2197) is happening right now. +* Dmitrii made a new [music video with his metal band](https://twitter.com/abramov_dmitrii/status/806613542447157248). +* [lazyspec](https://yarnpkg.com/en/package/lazyspec) can help you create smoke tests quickly if you are introducing tests to an existing codebase. +* Patrick Stapfer did a lightning talk about [vim and Jest](https://twitter.com/ryyppy/status/803871975995277312). +* Mark Dalgleish was [commenting on the value of snapshot testing](https://twitter.com/markdalgleish/status/806608159527747584). ## New features, changes and fixes in Jest 17 & 18 -Jest was initially created more than five years ago and as such an old framework -it has accumulated some technical debt. This is why we tend to make breaking -changes more often than may seem necessary: We believe it is important to -incrementally reduce technical debt to ensure that Jest as a project stays -maintainable long-term. We didn't announce Jest 17 in a blog post and if you -haven't upgraded to it in the last month you may find the -[changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md) useful. +Jest was initially created more than five years ago and as such an old framework it has accumulated some technical debt. This is why we tend to make breaking changes more often than may seem necessary: We believe it is important to incrementally reduce technical debt to ensure that Jest as a project stays maintainable long-term. We didn't announce Jest 17 in a blog post and if you haven't upgraded to it in the last month you may find the [changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md) useful. -* **Breaking:** Removed `pit` in favor of `it` or `test` and `mockImpl` in favor - of `jest.fn()` or `mockImplementation` . +* **Breaking:** Removed `pit` in favor of `it` or `test` and `mockImpl` in favor of `jest.fn()` or `mockImplementation` . * **Breaking:** Renamed `--jsonOutputFile` to `--outputFile`. * **Breaking:** Updated `testRegex` to include `test.js` and `spec.js` files. * **Breaking:** Replaced `scriptPreprocessor` with the new `transform` option. -* **Breaking:** The `testResultsProcessor` function is now required to return - the modified results. -* **Potentially Breaking:** Properly resolve `snapshotSerializers`, - `setupFiles`, `transform`, `testRunner` and `testResultsProcessor` with a - resolution algorithm instead of using `path.resolve`. This mainly means that - `` is no longer needed for these options. +* **Breaking:** The `testResultsProcessor` function is now required to return the modified results. +* **Potentially Breaking:** Properly resolve `snapshotSerializers`, `setupFiles`, `transform`, `testRunner` and `testResultsProcessor` with a resolution algorithm instead of using `path.resolve`. This mainly means that `` is no longer needed for these options. * **Added: **`pretty-format` and `jest-editor-support` were merged into Jest. -* **Added:** `expect.any`, `expect.anything`, `expect.objectContaining`, - `expect.arrayContaining`, `expect.stringMatching`. +* **Added:** `expect.any`, `expect.anything`, `expect.objectContaining`, `expect.arrayContaining`, `expect.stringMatching`. * **Added: **`--testResultsProcessor` is now exposed through the cli. * **Added:** Implemented file watching in `jest-haste-map`. -* **Added:** 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:** 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: **`.toMatchSnapshot(?string)` feature to give snapshots a name. * **Added: **`toMatchObject`, `toHaveProperty` , `toHaveLength` matchers. * **Added:** `expect.extend`. * **Added:** Added support for custom snapshots serializers. -* **Added:** Big diffs are now collapsed by default in snapshots and assertions. - Added `--expand` (or `-e`) to show the full diff. +* **Added:** Big diffs are now collapsed by default in snapshots and assertions. Added `--expand` (or `-e`) to show the full diff. * **Added:** `jest.resetAllMocks` which replaces `jest.clearAllMocks`. -* **Added: **`--json` now includes information about individual tests inside a - file. +* **Added: **`--json` now includes information about individual tests inside a file. * **Fixed: **`test.concurrent` unhandled promise rejections. -* **Fixed:** `babel-plugin-jest-hoist` when using `jest.mock` with three - arguments. -* **Fixed:** The `JSON` global in `jest-environment-node` now comes from the vm - context instead of the parent context. +* **Fixed:** `babel-plugin-jest-hoist` when using `jest.mock` with three arguments. +* **Fixed:** The `JSON` global in `jest-environment-node` now comes from the vm context instead of the parent context. * **Fixed:** Jest does not print stack traces from babel any longer. * **Fixed:** Fake timers are reset when `FakeTimers.useTimers()` is called. * **Fixed:** Regular expressions are properly escaped in snapshots. * **Fixed:** Improved pretty printing of large objects. * **Fixed:** `NaN% Failed` in the OS notification when using `--notify`. -* **Fixed:** The first test run without cached timings will now use separate - processes instead of running in band. +* **Fixed:** The first test run without cached timings will now use separate processes instead of running in band. * **Fixed:** `Map`/`Set` comparisons. * **Fixed: **`test.concurrent` now works with `--testNamePattern`. * **Fixed:** Improved `.toContain` matcher. * **Fixed:** Properly resolve modules with platform extensions on react-native. -* **Fixed:** global built in objects in `jest-environment-node` now work - properly. -* **Fixed:** Create mock objects in the vm context instead of the parent - context. +* **Fixed:** global built in objects in `jest-environment-node` now work properly. +* **Fixed:** Create mock objects in the vm context instead of the parent context. * **Fixed: **`.babelrc` is now part of the transform cache key in `babel-jest`. * **Fixed:** docblock parsing with haste modules. -* **Fixed:** Exit with the proper code when the coverage threshold is not - reached. +* **Fixed:** Exit with the proper code when the coverage threshold is not reached. * **Fixed: **Jest now clears the entire scrollback in watch mode. -* **Deprecated: **`jest-react-native` was deprecated and now forwards - `react-native`. +* **Deprecated: **`jest-react-native` was deprecated and now forwards `react-native`. ## Plans for Jest in H1 2017 -Six months ago -[we shared our plans for Jest](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html#what-s-next-for-jest) -and we are happy that we were able to execute well on almost all of them. For -the next six months, here is what we are planning: +Six months ago [we shared our plans for Jest](http://facebook.github.io/jest/blog/2016/07/27/jest-14.html#what-s-next-for-jest) and we are happy that we were able to execute well on almost all of them. For the next six months, here is what we are planning: -* **Instant feedback:** [Nuclide](https://nuclide.io/) integration and an - improved and - [faster watch mode](https://github.com/facebook/jest/pull/2324#issuecomment-267149669). +* **Instant feedback:** [Nuclide](https://nuclide.io/) integration and an improved and [faster watch mode](https://github.com/facebook/jest/pull/2324#issuecomment-267149669). * **Improved developer experience:** new mocking APIs and improved assertions. -* **Better performance and memory usage:** analyze Jest and be more conscious - about efficiency. -* **Snapshot Improvements: **snapshot approval mode, syntax highlighting and - improved `react-test-renderer` APIs. -* **Website:** We'll overhaul the website and documentation and add a Jest cheat - sheet. - -We won't be providing timelines or estimates for these features and we may not -actually get to all of these things. If you'd like to help make these things a -reality, send us issues and pull requests with your ideas and let's work on -improving Jest together in 2017. +* **Better performance and memory usage:** analyze Jest and be more conscious about efficiency. +* **Snapshot Improvements: **snapshot approval mode, syntax highlighting and improved `react-test-renderer` APIs. +* **Website:** We'll overhaul the website and documentation and add a Jest cheat sheet. + +We won't be providing timelines or estimates for these features and we may not actually get to all of these things. If you'd like to help make these things a reality, send us issues and pull requests with your ideas and let's work on improving Jest together in 2017. diff --git a/website/blog/2017-01-30-a-great-developer-experience.md b/website/blog/2017-01-30-a-great-developer-experience.md index a66c7fc3c27c..e814611e167e 100644 --- a/website/blog/2017-01-30-a-great-developer-experience.md +++ b/website/blog/2017-01-30-a-great-developer-experience.md @@ -5,49 +5,27 @@ authorURL: http://twitter.com/hectorramos authorFBID: 121800083 --- -We strongly believe that great documentation is crucial to providing a great -developer experience. The docs should be clear, concise, and useful to new users -and veterans alike. With that in mind, we recently took some time to overhaul -the Jest website. +We strongly believe that great documentation is crucial to providing a great developer experience. The docs should be clear, concise, and useful to new users and veterans alike. With that in mind, we recently took some time to overhaul the Jest website. ## Improved docs -One of the changes you'll notice upon visiting our docs is the updated sidebar. -The documentation is now divided into three main areas: an introduction to Jest, -detailed guides to Jest's features, and a comprehensive API reference. +One of the changes you'll notice upon visiting our docs is the updated sidebar. The documentation is now divided into three main areas: an introduction to Jest, detailed guides to Jest's features, and a comprehensive API reference. -The **Introduction** section will guide you from installing Jest and writing -your first case, to using Jest's matchers and testing async code. If you're new -to Jest or need a quick refresher, these docs should get you up to speed in no -time. If you've used Jest before and only need a quick reference on how it's -installed, you need to go no further than the -[Getting Started](/jest/docs/getting-started.html) guide. +The **Introduction** section will guide you from installing Jest and writing your first case, to using Jest's matchers and testing async code. If you're new to Jest or need a quick refresher, these docs should get you up to speed in no time. If you've used Jest before and only need a quick reference on how it's installed, you need to go no further than the [Getting Started](/jest/docs/getting-started.html) guide. -Once you feel comfortable using Jest, proceed to the advanced **Guides** -section. The new [Snapshot Testing guide](/jest/docs/snapshot-testing.html) -covers everything you need to know about creating and maintaining snapshot test -cases. +Once you feel comfortable using Jest, proceed to the advanced **Guides** section. The new [Snapshot Testing guide](/jest/docs/snapshot-testing.html) covers everything you need to know about creating and maintaining snapshot test cases. -Finally, we've completely overhauled our API reference docs. You can now find -detailed information on all of Jest's [Globals](/jest/docs/api.html), -[matchers](/jest/docs/expect.html), and [every flag](/jest/docs/cli.html) -supported by the `jest` CLI. +Finally, we've completely overhauled our API reference docs. You can now find detailed information on all of Jest's [Globals](/jest/docs/api.html), [matchers](/jest/docs/expect.html), and [every flag](/jest/docs/cli.html) supported by the `jest` CLI. ## New colors & website -The colors in the Jest logo and on the website have felt outdated to us for a -while. We changed the color scheme we are using for Jest and changed the landing -page significantly to be more inviting. We hope you like the new colors and -showcase of Jest's strengths. +The colors in the Jest logo and on the website have felt outdated to us for a while. We changed the color scheme we are using for Jest and changed the landing page significantly to be more inviting. We hope you like the new colors and showcase of Jest's strengths. ## Who's using Jest? -We have created a [showcase of users](/jest/users.html) to highlight some of the -companies that are using Jest. We're thankful to all of these companies for -using Jest to test their websites, mobile apps, and APIs. If you're using Jest, -check out the guidelines on GitHub and send us a pull request! +We have created a [showcase of users](/jest/users.html) to highlight some of the companies that are using Jest. We're thankful to all of these companies for using Jest to test their websites, mobile apps, and APIs. If you're using Jest, check out the guidelines on GitHub and send us a pull request!
@@ -61,11 +39,7 @@ check out the guidelines on GitHub and send us a pull request! ## Jest in the browser -As highlighted [last month](/jest/blog/2016/12/15/2016-in-jest.html), it is now -possible to use Jest directly in the browser using -[repl.it](https://repl.it/languages/jest). If you want to try out Jest before -installing it, you can easily do so below or directly from the Jest homepage. Go -ahead and give it a try! +As highlighted [last month](/jest/blog/2016/12/15/2016-in-jest.html), it is now possible to use Jest directly in the browser using [repl.it](https://repl.it/languages/jest). If you want to try out Jest before installing it, you can easily do so below or directly from the Jest homepage. Go ahead and give it a try!
@@ -73,11 +47,6 @@ ahead and give it a try! ## Get involved -This is just the start. Go ahead and take a look at the docs, and don't hesitate -to send any feedback our way. If you find a mistake in the docs or you just want -to let us know what needs to be documented better, please tweet at us at -[@fbjest](https://twitter.com/fbjest), -[open an issue on GitHub](https://github.com/facebook/jest/issues), or send us a -PR by clicking "Edit on GitHub" at the top of the doc. +This is just the start. Go ahead and take a look at the docs, and don't hesitate to send any feedback our way. If you find a mistake in the docs or you just want to let us know what needs to be documented better, please tweet at us at [@fbjest](https://twitter.com/fbjest), [open an issue on GitHub](https://github.com/facebook/jest/issues), or send us a PR by clicking "Edit on GitHub" at the top of the doc. We're really excited for the year ahead and can't wait to hear from you! diff --git a/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md b/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md index 916375b20c94..85f3e9d69e54 100644 --- a/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md +++ b/website/blog/2017-02-21-jest-19-immersive-watch-mode-test-platform-improvements.md @@ -5,31 +5,20 @@ authorURL: http://twitter.com/rogeliog authorFBID: 511230566 --- -Today we are pleased to ship version 19 of the Jest testing platform. It's the -biggest Jest release we have shipped so far and we are quite excited to show you -what we've built over the last two months: +Today we are pleased to ship version 19 of the Jest testing platform. It's the biggest Jest release we have shipped so far and we are quite excited to show you what we've built over the last two months: ## Immersive Watch Mode -We -[completely rewrote the watch mode](https://github.com/facebook/jest/pull/2362) -to make it instant and more extensible. As a result, the experience of using it -really is immersive: tests re-run instantly after a file change and we made it -easy to select the right tests. +We [completely rewrote the watch mode](https://github.com/facebook/jest/pull/2362) to make it instant and more extensible. As a result, the experience of using it really is immersive: tests re-run instantly after a file change and we made it easy to select the right tests. ## Snapshot Updates -We made a couple of changes to the snapshot format. We don't make changes like -this often and only consider them if they actually improve how snapshots work. -As well as introducing a snapshot version number we accumulated a number of -changes we wanted to make to the format for a while: +We made a couple of changes to the snapshot format. We don't make changes like this often and only consider them if they actually improve how snapshots work. As well as introducing a snapshot version number we accumulated a number of changes we wanted to make to the format for a while: -* We dropped the “test” prefix in snapshot names from top level `test` or `it` - calls. -* We improved the printing of React elements to cause less changes when the last - prop in an element changes. +* We dropped the “test” prefix in snapshot names from top level `test` or `it` calls. +* We improved the printing of React elements to cause less changes when the last prop in an element changes. * We improved the character escaping mechanism to be more bulletproof. Before: @@ -63,35 +52,26 @@ exports[`snap 1`] = ` `; ``` -We decided it's a good time to introduce versioned snapshots to ensure all -developers are using a compatible version of Jest. Here's how we warn you about -the need to update your snapshot: +We decided it's a good time to introduce versioned snapshots to ensure all developers are using a compatible version of Jest. Here's how we warn you about the need to update your snapshot: ![snapshot-version](/jest/img/blog/19-snapshot-version.png) -Please make sure you revert any local changes before updating to make the -transition smooth and to ensure you aren't including any unwanted changes from -failing tests in your new snapshots. +Please make sure you revert any local changes before updating to make the transition smooth and to ensure you aren't including any unwanted changes from failing tests in your new snapshots. ## Improved printing of skipped tests -Skipped tests are now printed as a single line instead of showing every -individual one when testing in verbose mode or a single suite. Hopefully it will -let you focus on currently important tests. It also occupies far less space! +Skipped tests are now printed as a single line instead of showing every individual one when testing in verbose mode or a single suite. Hopefully it will let you focus on currently important tests. It also occupies far less space! ![skipped-tests](/jest/img/blog/19-skipped-tests.png) ## New CLI arguments -Jest 19 ships with two new coverage-related arguments which you can run from -CLI: +Jest 19 ships with two new coverage-related arguments which you can run from CLI: * `--collectCoverageFrom` * `--coverageDirectory` -We now also error on invalid CLI arguments instead of ignoring them. But we've -got your back with helpful error message like the one below, e.g. when you try -running `jest --watc`: +We now also error on invalid CLI arguments instead of ignoring them. But we've got your back with helpful error message like the one below, e.g. when you try running `jest --watc`: ![cli-error](/jest/img/blog/19-cli-error.png) @@ -101,156 +81,66 @@ running `jest --watc`: * [`expect.stringContaining`](/jest/docs/expect.html#expectstringcontainingstring) * [`jest.spyOn`](/jest/docs/jest-object.html#jestspyonobject-methodname) -We're close to almost full feature parity with the `expect` npm package. -[Michael Jackson](https://twitter.com/mjackson), the author of the package, -agreed to [donate](https://github.com/facebook/jest/issues/1679) it to the Jest -project, which means that `jest-matchers` will be renamed to `expect`. Since our -version of `expect` is not intended to be fully compatible, -[Christopher Chedeau](https://twitter.com/Vjeux) is working on a codemod to make -the transition painless. Christopher also worked on a number of improvements to -`jest-matchers` which enables it to be used outside of Jest and even -[works inside browsers](https://github.com/facebook/jest/pull/2795). +We're close to almost full feature parity with the `expect` npm package. [Michael Jackson](https://twitter.com/mjackson), the author of the package, agreed to [donate](https://github.com/facebook/jest/issues/1679) it to the Jest project, which means that `jest-matchers` will be renamed to `expect`. Since our version of `expect` is not intended to be fully compatible, [Christopher Chedeau](https://twitter.com/Vjeux) is working on a codemod to make the transition painless. Christopher also worked on a number of improvements to `jest-matchers` which enables it to be used outside of Jest and even [works inside browsers](https://github.com/facebook/jest/pull/2795). ## [eslint-plugin-jest](https://github.com/facebook/jest/tree/master/packages/eslint-plugin-jest) – our very own ESLint plugin -Thanks to [Jonathan Kim](https://twitter.com/jonnykim) Jest finally has its own -official ESLint plugin. It exposes three rules: +Thanks to [Jonathan Kim](https://twitter.com/jonnykim) Jest finally has its own official ESLint plugin. It exposes three rules: -* [no-disabled-tests](https://github.com/facebook/jest/blob/master/packages/eslint-plugin-jest/docs/rules/no-disabled-tests.md) - - this rule prevents you from accidentally committing disabled tests. -* [no-focused-tests](https://github.com/facebook/jest/blob/master/packages/eslint-plugin-jest/docs/rules/no-focused-tests.md) - - this rule prevents you from committing focused tests which would disable all - other tests in the same suite. -* [no-identical-title](https://github.com/facebook/jest/blob/master/packages/eslint-plugin-jest/docs/rules/no-identical-title.md) - - disallows identical titles in test names. +* [no-disabled-tests](https://github.com/facebook/jest/blob/master/packages/eslint-plugin-jest/docs/rules/no-disabled-tests.md) - this rule prevents you from accidentally committing disabled tests. +* [no-focused-tests](https://github.com/facebook/jest/blob/master/packages/eslint-plugin-jest/docs/rules/no-focused-tests.md) - this rule prevents you from committing focused tests which would disable all other tests in the same suite. +* [no-identical-title](https://github.com/facebook/jest/blob/master/packages/eslint-plugin-jest/docs/rules/no-identical-title.md) - disallows identical titles in test names. -You can install it using `npm install --save-dev eslint-plugin-jest` or -`yarn add --dev eslint eslint-plugin-jest` and it can be enabled by adding -`{"plugins": ["jest"]}` to your eslint configuration. +You can install it using `npm install --save-dev eslint-plugin-jest` or `yarn add --dev eslint eslint-plugin-jest` and it can be enabled by adding `{"plugins": ["jest"]}` to your eslint configuration. ## New public package: [jest-validate](https://github.com/facebook/jest/tree/master/packages/jest-validate) -While we refactored the validation and normalization code for Jest's -configuration, we were so happy with the new error messaging that we extracted -it to its own module to share it with everyone. With Jest 19 we welcome -`jest-validate` to our self-sustained packages family. +While we refactored the validation and normalization code for Jest's configuration, we were so happy with the new error messaging that we extracted it to its own module to share it with everyone. With Jest 19 we welcome `jest-validate` to our self-sustained packages family. -`jest-validate` is a generic configuration validation tool that helps you with -warnings, errors and deprecation messages in your JavaScript tool. It's also -capable of showing users friendly examples of correct configuration and it comes -with a simple but powerful API. We hope it'll make a good addition to your -projects! +`jest-validate` is a generic configuration validation tool that helps you with warnings, errors and deprecation messages in your JavaScript tool. It's also capable of showing users friendly examples of correct configuration and it comes with a simple but powerful API. We hope it'll make a good addition to your projects! ![validate](/jest/img/blog/19-validate.png) -We're happy to announce that `jest-validate` is validating config options of -[prettier](https://github.com/jlongster/prettier) since -[v0.12](https://github.com/jlongster/prettier/blob/master/CHANGELOG.md#0120). -Feel free to add it to your project, try it, send us feedback and improve it by -making pull requests on GitHub. +We're happy to announce that `jest-validate` is validating config options of [prettier](https://github.com/jlongster/prettier) since [v0.12](https://github.com/jlongster/prettier/blob/master/CHANGELOG.md#0120). Feel free to add it to your project, try it, send us feedback and improve it by making pull requests on GitHub. ## Improved asymmetric matchers -We moved the asymmetric matchers implementation from Jasmine into Jest, which -enabled us to further improve the user experience around them. As a result, -asymmetric matchers are now pretty-printed nicely, we added the new -[`expect.stringContaining()`](http://facebook.github.io/jest/docs/expect.html#expectstringcontainingstring) -matcher and we also paired them with -[`expect.toMatchObject()`](http://facebook.github.io/jest/docs/expect.html#tomatchobjectobject) -so you can use the best of both: +We moved the asymmetric matchers implementation from Jasmine into Jest, which enabled us to further improve the user experience around them. As a result, asymmetric matchers are now pretty-printed nicely, we added the new [`expect.stringContaining()`](http://facebook.github.io/jest/docs/expect.html#expectstringcontainingstring) matcher and we also paired them with [`expect.toMatchObject()`](http://facebook.github.io/jest/docs/expect.html#tomatchobjectobject) so you can use the best of both: ![asymmetric-matchers](/jest/img/blog/19-asymmetric-matchers.png) ## Better manual mocks -With the latest release, manual mocks now finally work with nested folders. For -example `__mocks__/react-native/Libraries/Text/Text.js` will now work as -expected and mock the correct module. We also fixed issues with virtual mocks -and transitive dependencies and improved `moduleNameMapper` to not overwrite -mocks when many patterns map to the same file. +With the latest release, manual mocks now finally work with nested folders. For example `__mocks__/react-native/Libraries/Text/Text.js` will now work as expected and mock the correct module. We also fixed issues with virtual mocks and transitive dependencies and improved `moduleNameMapper` to not overwrite mocks when many patterns map to the same file. ## Breaking Changes -As a part of our cleanups and fixes we removed the `mocksPattern` configuration -option which was never officially supported. We also renamed the `testPathDirs` -configuration option to `roots` which better explains what the option can be -used for. The default configuration for `roots` is `[""]` and can be -customized to include any number of directories. The rootDir configuration -option has always been used mostly as a token for other configuration options -and this rename should make configuring Jest clearer. +As a part of our cleanups and fixes we removed the `mocksPattern` configuration option which was never officially supported. We also renamed the `testPathDirs` configuration option to `roots` which better explains what the option can be used for. The default configuration for `roots` is `[""]` and can be customized to include any number of directories. The rootDir configuration option has always been used mostly as a token for other configuration options and this rename should make configuring Jest clearer. ## Revamped documentation -As you may have already seen, [Hector Ramos](https://twitter.com/hectorramos) -and [Kevin Lacker](https://twitter.com/lacker) gave Jest's documentation a fresh -new look. We changed the way we organize the website and it now features Docs -and API as separate pages: - -* Under - [Docs](https://facebook.github.io/jest/docs/getting-started.html#content) you - can find an introduction to Jest, including - [Getting Started](https://facebook.github.io/jest/docs/getting-started.html#content) - or - [Testing Asynchronous Code](https://facebook.github.io/jest/docs/asynchronous.html#content) - and handy guides like - [Snapshot Testing](https://facebook.github.io/jest/docs/snapshot-testing.html#content), - [Testing React Native App](https://facebook.github.io/jest/docs/tutorial-react-native.html#content), - [Using with webpack](https://facebook.github.io/jest/docs/webpack.html#content) - or - [Migrating to Jest](https://facebook.github.io/jest/docs/migration-guide.html#content) - and many more! -* The [API](https://facebook.github.io/jest/docs/api.html) section on the other - hand lists all available methods exposed by Jest: the `expect` and `jest` - objects, mock functions, globals, along with configuration options from - _package.json_ and from the CLI. - -The homepage was completely redesigned to be more descriptive of what Jest is -about: “_Zero configuration testing platform_”. We also made sure it reads -better on mobile devices. And for those using RSS – we finally provide a -[feed for our blog](http://facebook.github.io/jest/blog/feed.xml). +As you may have already seen, [Hector Ramos](https://twitter.com/hectorramos) and [Kevin Lacker](https://twitter.com/lacker) gave Jest's documentation a fresh new look. We changed the way we organize the website and it now features Docs and API as separate pages: + +* Under [Docs](https://facebook.github.io/jest/docs/getting-started.html#content) you can find an introduction to Jest, including [Getting Started](https://facebook.github.io/jest/docs/getting-started.html#content) or [Testing Asynchronous Code](https://facebook.github.io/jest/docs/asynchronous.html#content) and handy guides like [Snapshot Testing](https://facebook.github.io/jest/docs/snapshot-testing.html#content), [Testing React Native App](https://facebook.github.io/jest/docs/tutorial-react-native.html#content), [Using with webpack](https://facebook.github.io/jest/docs/webpack.html#content) or [Migrating to Jest](https://facebook.github.io/jest/docs/migration-guide.html#content) and many more! +* The [API](https://facebook.github.io/jest/docs/api.html) section on the other hand lists all available methods exposed by Jest: the `expect` and `jest` objects, mock functions, globals, along with configuration options from _package.json_ and from the CLI. + +The homepage was completely redesigned to be more descriptive of what Jest is about: “_Zero configuration testing platform_”. We also made sure it reads better on mobile devices. And for those using RSS – we finally provide a [feed for our blog](http://facebook.github.io/jest/blog/feed.xml). ## Community Updates -* We really loved this talk: - “[Introduction to Jest](https://www.youtube.com/watch?v=tvy0bSgwtTo)“ by Vas - Boroviak. +* We really loved this talk: “[Introduction to Jest](https://www.youtube.com/watch?v=tvy0bSgwtTo)“ by Vas Boroviak. * Follow [@fbjest on Twitter](http://twitter.com/fbjest). -* The Jest Core team syncs once a week to discuss current and future issues. If - you'd like to work on Jest, let us know, submit a few pull requests and join - our weekly team meetings. -* The awesome engineers at Artsy wrote - [about Jest as part of their 2017 frontend stack](http://artsy.github.io/blog/2017/02/05/Front-end-JavaScript-at-Artsy-2017/). -* Stephen Scott wrote a detailed article about - [testing React components](https://medium.freecodecamp.com/the-right-way-to-test-react-components-548a4736ab22) - in which he weighs the pros and cons of different approaches. -* [Using Jest with vue.js](https://medium.com/@kentaromiura_the_js_guy/jest-for-all-episode-1-vue-js-d616bccbe186#.r8ryxlw98) - got a lot easier after reading Cristian Carlesso's blog post. -* [Michele Bertoli wrote a book about React Design Patterns and Best Practices](https://twitter.com/cpojer/status/825004258219130880) - which features an entire section about Jest. -* Improved `--notify` command that shows an operating system notification which - [can now also re-run tests from the notification](https://github.com/facebook/jest/pull/2727). - This is actually a Jest feature and we are just checking if you are still - reading this blog post. -* Jest is now part of - [react-boilerplate](https://twitter.com/mxstbr/status/820326656439177217). -* Read about the - [hidden powers of Jest's matchers](https://medium.com/@boriscoder/the-hidden-power-of-jest-matchers-f3d86d8101b0#.pn10z1pzx). - -Finally, we are happy to announce that the [ava](https://github.com/avajs/ava) -test runner has adopted parts of the Jest platform and is now shipping with -basic [snapshot support](https://github.com/avajs/ava#snapshot-testing) and is -using -[pretty-format](https://github.com/facebook/jest/tree/master/packages/pretty-format). -Consolidating test infrastructure makes it easier to learn how to test -applications and enables us to share best practices. We are looking forward to -see what we can learn from existing test libraries in the future. - -The full -[changelog can be found on GitHub](https://github.com/facebook/jest/blob/master/CHANGELOG.md#jest-1900). -Jest 19 was a true JavaScript community effort with -[17 people who contributed](https://github.com/facebook/jest/graphs/contributors?from=2016-12-23&to=2017-02-21&type=c) -to this release. We thank each and every one of you for your help to make this -project great. - -_This blog post was written by [Rogelio Guzman](https://twitter.com/rogeliog) -and [Michał Pierzchała](https://twitter.com/thymikee)._ +* The Jest Core team syncs once a week to discuss current and future issues. If you'd like to work on Jest, let us know, submit a few pull requests and join our weekly team meetings. +* The awesome engineers at Artsy wrote [about Jest as part of their 2017 frontend stack](http://artsy.github.io/blog/2017/02/05/Front-end-JavaScript-at-Artsy-2017/). +* Stephen Scott wrote a detailed article about [testing React components](https://medium.freecodecamp.com/the-right-way-to-test-react-components-548a4736ab22) in which he weighs the pros and cons of different approaches. +* [Using Jest with vue.js](https://medium.com/@kentaromiura_the_js_guy/jest-for-all-episode-1-vue-js-d616bccbe186#.r8ryxlw98) got a lot easier after reading Cristian Carlesso's blog post. +* [Michele Bertoli wrote a book about React Design Patterns and Best Practices](https://twitter.com/cpojer/status/825004258219130880) which features an entire section about Jest. +* Improved `--notify` command that shows an operating system notification which [can now also re-run tests from the notification](https://github.com/facebook/jest/pull/2727). This is actually a Jest feature and we are just checking if you are still reading this blog post. +* Jest is now part of [react-boilerplate](https://twitter.com/mxstbr/status/820326656439177217). +* Read about the [hidden powers of Jest's matchers](https://medium.com/@boriscoder/the-hidden-power-of-jest-matchers-f3d86d8101b0#.pn10z1pzx). + +Finally, we are happy to announce that the [ava](https://github.com/avajs/ava) test runner has adopted parts of the Jest platform and is now shipping with basic [snapshot support](https://github.com/avajs/ava#snapshot-testing) and is using [pretty-format](https://github.com/facebook/jest/tree/master/packages/pretty-format). Consolidating test infrastructure makes it easier to learn how to test applications and enables us to share best practices. We are looking forward to see what we can learn from existing test libraries in the future. + +The full [changelog can be found on GitHub](https://github.com/facebook/jest/blob/master/CHANGELOG.md#jest-1900). Jest 19 was a true JavaScript community effort with [17 people who contributed](https://github.com/facebook/jest/graphs/contributors?from=2016-12-23&to=2017-02-21&type=c) to this release. We thank each and every one of you for your help to make this project great. + +_This blog post was written by [Rogelio Guzman](https://twitter.com/rogeliog) and [Michał Pierzchała](https://twitter.com/thymikee)._ diff --git a/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md b/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md index 256a58bf0889..a5e1218ff6f2 100644 --- a/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md +++ b/website/blog/2017-05-06-jest-20-delightful-testing-multi-project-runner.md @@ -5,44 +5,19 @@ authorURL: http://twitter.com/cpojer authorFBID: 100000023028168 --- -A few months ago we announced -[Jest 19](http://facebook.github.io/jest/blog/2017/02/21/jest-19-immersive-watch-mode-test-platform-improvements.html) -which came with major new features and was the biggest Jest release until today. -Jest 20 has twice the amount of changes compared to the previous version, -features a complete rewrite of the test runner, adds new testing APIs. The new -release enables a new level of customization and configuration for projects all -while making it effortless to upgrade. Beyond Painless JavaScript Testing, we -believe Jest is now delivering a **Delightful JavaScript Testing experience**. -Let's take a look at the best new features and changes in depth: +A few months ago we announced [Jest 19](http://facebook.github.io/jest/blog/2017/02/21/jest-19-immersive-watch-mode-test-platform-improvements.html) which came with major new features and was the biggest Jest release until today. Jest 20 has twice the amount of changes compared to the previous version, features a complete rewrite of the test runner, adds new testing APIs. The new release enables a new level of customization and configuration for projects all while making it effortless to upgrade. Beyond Painless JavaScript Testing, we believe Jest is now delivering a **Delightful JavaScript Testing experience**. Let's take a look at the best new features and changes in depth: ## Multi-Project-Runner & Configuration Overhaul -Until now, Jest could only operate in one project at a time. This is often -cumbersome if you are working on many smaller projects that each have their own -setup and configuration. With Jest 20, we rewrote the test runner completely to -run many projects at the same time within a single instance of Jest, for example -if you are working on a React frontend and a node.js backend. Here is a video of -Jest running tests for [React](https://github.com/facebook/react), -[Relay](https://github.com/facebook/relay), -[Yarn](https://github.com/yarnpkg/yarn) and Jest all at the same time: +Until now, Jest could only operate in one project at a time. This is often cumbersome if you are working on many smaller projects that each have their own setup and configuration. With Jest 20, we rewrote the test runner completely to run many projects at the same time within a single instance of Jest, for example if you are working on a React frontend and a node.js backend. Here is a video of Jest running tests for [React](https://github.com/facebook/react), [Relay](https://github.com/facebook/relay), [Yarn](https://github.com/yarnpkg/yarn) and Jest all at the same time: ![multi-runner](/jest/img/blog/20-multi-runner.gif) -Jest is now collapsing the usage guide after the first test run to save vertical -space in the terminal. +Jest is now collapsing the usage guide after the first test run to save vertical space in the terminal. -Further, we completely overhauled how the configuration system works inside of -Jest. You can now pass any configuration option through the CLI to overwrite the -ones specified in your configuration file. Along with that, we changed Jest to -look for a `jest.config.js` file by default which means you are now able to -define a Jest configuration using JavaScript as well as being able to configure -it through `package.json` like before. Through the addition of all these new -features, you are now able to combine Jest in more powerful ways than ever -before. For example, if you would like to find out which tests Jest would run -given a set of changed files from a commit across multiple projects in a -monorepo, you can combine cli arguments like this now: +Further, we completely overhauled how the configuration system works inside of Jest. You can now pass any configuration option through the CLI to overwrite the ones specified in your configuration file. Along with that, we changed Jest to look for a `jest.config.js` file by default which means you are now able to define a Jest configuration using JavaScript as well as being able to configure it through `package.json` like before. Through the addition of all these new features, you are now able to combine Jest in more powerful ways than ever before. For example, if you would like to find out which tests Jest would run given a set of changed files from a commit across multiple projects in a monorepo, you can combine cli arguments like this now: ``` $ jest --projects projectA projectB --listTests --findRelatedTests projectA/banana.js projectB/kiwi.js @@ -53,41 +28,21 @@ $ jest --projects projectA projectB --listTests --findRelatedTests projectA/bana ] ``` -This is especially useful for continuous integration (CI) systems where you may -want to only run a subset of tests for Pull Requests to prevent Jest from -running thousands of test files on every small change. +This is especially useful for continuous integration (CI) systems where you may want to only run a subset of tests for Pull Requests to prevent Jest from running thousands of test files on every small change. -Finally, we are now properly mapping code coverage when using TypeScript and we -are running code coverage for untested files in worker processes which yields -significant speed ups for this feature. +Finally, we are now properly mapping code coverage when using TypeScript and we are running code coverage for untested files in worker processes which yields significant speed ups for this feature. ## New & Improved Testing APIs -We made a number of additions and improvements to the testing APIs which will -help write more effective tests. We'd like to point out that all of these -improvements were made entirely by community members! - -* **Better async testing:** Added new async/Promise support through - resolves/rejects modifiers on expect: - `expect(Promise(…)).resolves.toEqual(…)`. - [See documentation](https://facebook.github.io/jest/docs/en/expect.html#resolves). -* **Expect assertions:** Along with the existing `expect.assertions(n)`, the - new `expect.hasAssertions()` can be used to ensure a test has at least one - assertion. -* **Lint Plugin:** A `valid-expect` rule was added to `eslint-plugin-jest` to - ensure that an assertion is called after invoking `expect`. This will prevent - mistakes like a stray `expect(banana);` with a missing assertion call. -* **Pretty-Format Plugins:** A number of new pretty-format plugins were added to - Jest. We now pretty-print - [Immutable.js](https://github.com/facebook/immutable-js/) data structures and - HtmlElements in assertion failures and snapshots. -* **Custom Environment:** It is now possible to add a - `@jest-environment node|jsdom` annotation to the doc-block comment of a test - file to use a test environment different from the default for individual - tests. - -Here is an example of all how all the new APIs together will make testing more -delightful: +We made a number of additions and improvements to the testing APIs which will help write more effective tests. We'd like to point out that all of these improvements were made entirely by community members! + +* **Better async testing:** Added new async/Promise support through resolves/rejects modifiers on expect: `expect(Promise(…)).resolves.toEqual(…)`. [See documentation](https://facebook.github.io/jest/docs/en/expect.html#resolves). +* **Expect assertions:** Along with the existing `expect.assertions(n)`, the new `expect.hasAssertions()` can be used to ensure a test has at least one assertion. +* **Lint Plugin:** A `valid-expect` rule was added to `eslint-plugin-jest` to ensure that an assertion is called after invoking `expect`. This will prevent mistakes like a stray `expect(banana);` with a missing assertion call. +* **Pretty-Format Plugins:** A number of new pretty-format plugins were added to Jest. We now pretty-print [Immutable.js](https://github.com/facebook/immutable-js/) data structures and HtmlElements in assertion failures and snapshots. +* **Custom Environment:** It is now possible to add a `@jest-environment node|jsdom` annotation to the doc-block comment of a test file to use a test environment different from the default for individual tests. + +Here is an example of all how all the new APIs together will make testing more delightful: ``` /** @@ -111,72 +66,25 @@ This example will print a test failure similar to this: ## Breaking Changes -As with every major release, we are making a number of breaking changes to make -larger changes in the future possible and to push the testing experience to a -new level. This time, we tried our best to only break APIs that we don't expect -to affect the majority of Jest's users: - -* **Fork of Jasmine 2.5:** We finally decided to fork Jasmine itself and take - ownership over Jest's own test runner. This will allow us to improve all - aspects of the unit testing experience in the future but for now we are - focused on incremental rewrites and reducing the API surface. If you see a - test breaking as a result of a Jasmine API that is now missing, there should - be an equivalent feature on the `jest` or `expect` objects. As such, we have - removed many Jasmine features that aren't generally used in most codebases. -* **New Snapshots on CI:** Snapshots must always be committed along with the - test and the modules they are testing. We changed Jest to not save new - snapshots automatically in Continuous Integration (CI) environments or when - the `--ci` flag is specified. To overwrite this behavior, which is generally - not recommended, the `--updateSnapshot` flag can be used. -* **Babel-Polyfill:** Jest used to load `babel-polyfill` automatically when - using babel-jest which resulted in memory leaks inside of Jest. In most - versions of node, it is not necessary to load `babel-polyfill` so we removed - this auto-inclusion and instead changed Jest to only include - `regenerator-runtime` by default, which is commonly used to support - async/await in older versions of Node.js. If you need `babel-polyfill`, you - can manually require it in your setup files. +As with every major release, we are making a number of breaking changes to make larger changes in the future possible and to push the testing experience to a new level. This time, we tried our best to only break APIs that we don't expect to affect the majority of Jest's users: + +* **Fork of Jasmine 2.5:** We finally decided to fork Jasmine itself and take ownership over Jest's own test runner. This will allow us to improve all aspects of the unit testing experience in the future but for now we are focused on incremental rewrites and reducing the API surface. If you see a test breaking as a result of a Jasmine API that is now missing, there should be an equivalent feature on the `jest` or `expect` objects. As such, we have removed many Jasmine features that aren't generally used in most codebases. +* **New Snapshots on CI:** Snapshots must always be committed along with the test and the modules they are testing. We changed Jest to not save new snapshots automatically in Continuous Integration (CI) environments or when the `--ci` flag is specified. To overwrite this behavior, which is generally not recommended, the `--updateSnapshot` flag can be used. +* **Babel-Polyfill:** Jest used to load `babel-polyfill` automatically when using babel-jest which resulted in memory leaks inside of Jest. In most versions of node, it is not necessary to load `babel-polyfill` so we removed this auto-inclusion and instead changed Jest to only include `regenerator-runtime` by default, which is commonly used to support async/await in older versions of Node.js. If you need `babel-polyfill`, you can manually require it in your setup files. ## Other Improvements -* **Documentation:** Documentation is critical to share best practices and teach - everyone how to write effective tests which will lead to better software. Over - the last few weeks we have also expanded Jest's documentation to include a - Snapshot Testing FAQ, a guide with information about how to use Jest with - common JavaScript libraries as well as we documented the new features - mentioned above. -* **Translations:** We are now asking for your help to - [translate the Jest documentation](https://crowdin.com/project/jest) to make - it easier for people to learn how to use Jest. -* **Custom Reporters:** Jest now supports custom test reporters through the - `reporters` configuration option. You can finally customize the output of Jest - as well as integrate it with other tools by generating reports in formats such - as XML. - [See documentation](https://facebook.github.io/jest/docs/en/configuration.html#reporters-array-modulename-modulename-options). -* **Codebase Health:** It was only possible iterate so quickly in Jest because - we spent a significant amount of time on the health of the codebase. We were - one of the early adopters of [prettier](https://github.com/prettier/prettier), - we notably increased flow coverage, forked Jasmine to improve our test runner - library and we rewrote and refactored significant portions of Jest itself to - set up Jest for success in the future. -* **Bugfixes:** As always, we made plenty of bugfixes in Jest. The full - changelog can be found in the - [Jest repository](https://github.com/facebook/jest/blob/master/CHANGELOG.md#jest-2000). +* **Documentation:** Documentation is critical to share best practices and teach everyone how to write effective tests which will lead to better software. Over the last few weeks we have also expanded Jest's documentation to include a Snapshot Testing FAQ, a guide with information about how to use Jest with common JavaScript libraries as well as we documented the new features mentioned above. +* **Translations:** We are now asking for your help to [translate the Jest documentation](https://crowdin.com/project/jest) to make it easier for people to learn how to use Jest. +* **Custom Reporters:** Jest now supports custom test reporters through the `reporters` configuration option. You can finally customize the output of Jest as well as integrate it with other tools by generating reports in formats such as XML. [See documentation](https://facebook.github.io/jest/docs/en/configuration.html#reporters-array-modulename-modulename-options). +* **Codebase Health:** It was only possible iterate so quickly in Jest because we spent a significant amount of time on the health of the codebase. We were one of the early adopters of [prettier](https://github.com/prettier/prettier), we notably increased flow coverage, forked Jasmine to improve our test runner library and we rewrote and refactored significant portions of Jest itself to set up Jest for success in the future. +* **Bugfixes:** As always, we made plenty of bugfixes in Jest. The full changelog can be found in the [Jest repository](https://github.com/facebook/jest/blob/master/CHANGELOG.md#jest-2000). ## Talks about Jest -Recently the Jest core team and other contributors started to talk more about -Jest and the experience of working on Jest at conferences: - -* Rogelio Guzman did a talk about - [Jest Snapshots and Beyond](https://www.youtube.com/watch?time_continue=416&v=HAuXJVI_bUs) - at React Conf. -* I spoke about - [Building High-Quality JavaScript Tools](https://developers.facebook.com/videos/f8-2017/building-high-quality-javascript-tools/) - at Facebook's F8 conference. - -_As always, this release couldn't have been possible without you, the JavaScript -community. We are incredibly grateful that we get the opportunity to work on -improving JavaScript testing together. If you'd like to contribute to Jest, -please don't hesitate to reach out to us on -[GitHub](https://github.com/facebook/jest) or on -[Discord](https://discord.gg/MWRhKCj)._ +Recently the Jest core team and other contributors started to talk more about Jest and the experience of working on Jest at conferences: + +* Rogelio Guzman did a talk about [Jest Snapshots and Beyond](https://www.youtube.com/watch?time_continue=416&v=HAuXJVI_bUs) at React Conf. +* I spoke about [Building High-Quality JavaScript Tools](https://developers.facebook.com/videos/f8-2017/building-high-quality-javascript-tools/) at Facebook's F8 conference. + +_As always, this release couldn't have been possible without you, the JavaScript community. We are incredibly grateful that we get the opportunity to work on improving JavaScript testing together. If you'd like to contribute to Jest, please don't hesitate to reach out to us on [GitHub](https://github.com/facebook/jest) or on [Discord](https://discord.gg/MWRhKCj)._ diff --git a/website/blog/2017-12-18-jest-22.md b/website/blog/2017-12-18-jest-22.md index 2e0f4e7aedf7..8d53c4935012 100644 --- a/website/blog/2017-12-18-jest-22.md +++ b/website/blog/2017-12-18-jest-22.md @@ -5,53 +5,23 @@ authorURL: https://github.com/SimenB authorFBID: 100003004880942 --- -Today we are announcing a new major version of Jest which refines almost all -parts of Jest to provide a more solid testing foundation. Together with the Jest -community we made a number of changes across the board that will help you get -more out of Jest. We are also graduating the custom runners feature out of the -experimental stage and added a new package, `jest-worker`, for parallelizing -work across multiple processes. We have compiled a list of highlights below but -make sure to check out the (as always) -[massive changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md). +Today we are announcing a new major version of Jest which refines almost all parts of Jest to provide a more solid testing foundation. Together with the Jest community we made a number of changes across the board that will help you get more out of Jest. We are also graduating the custom runners feature out of the experimental stage and added a new package, `jest-worker`, for parallelizing work across multiple processes. We have compiled a list of highlights below but make sure to check out the (as always) [massive changelog](https://github.com/facebook/jest/blob/master/CHANGELOG.md). ## Good bye Node 4 & welcome JSDOM 11 -With this release we are dropping support for Node 4, mainly because one of our -main dependencies, JSDOM, ended their support. Jest now comes out of the box -with JSDOM 11 which features better support for SVGs, `requestAnimationFrame`, -`URL` and `URLSearchParams` built in, and -[much more](https://github.com/tmpvar/jsdom/blob/master/Changelog.md). +With this release we are dropping support for Node 4, mainly because one of our main dependencies, JSDOM, ended their support. Jest now comes out of the box with JSDOM 11 which features better support for SVGs, `requestAnimationFrame`, `URL` and `URLSearchParams` built in, and [much more](https://github.com/tmpvar/jsdom/blob/master/Changelog.md). ## Custom Runners + Easy parallelization with `jest-worker` -In Jest 21 we introduced the concept of custom Jest runners. Since then, -Rogelio, one of Jest's core contributors, built a number of useful runners: If -you have many existing tests written using another framework but you'd like to -immediately benefit from Jest's features, check out -[jest-runner-mocha](https://yarnpkg.com/en/package/jest-runner-mocha). If you -have a large codebase that needs linting, -[you may get a significant speedup](https://twitter.com/lencioni/status/907398856756695040) -if you run eslint within Jest using -[jest-runner-eslint](https://yarnpkg.com/en/package/jest-runner-eslint). - -To gain more of fine-grained control over heavy tasks parallelization (e.g. -transforming files or crawling the file system), we designed a new library -perfectly suited for the job. We developed a modern, Promise-based module with -an approachable API, called `jest-worker`, that allows you to delegate to child -processes those intensive functions. As `jest-worker`, like any other Jest -package, is a part of the Jest platform, you can use it however you like even -without ever using Jest itself. You'll find more in the documentation -[here](https://yarnpkg.com/en/package/jest-worker). - -To get a better understanding of custom runners and Jest as a platform, make -sure to check out Rogelio's talk from Reactive Conf 2017: -[Jest as a Platform](https://www.youtube.com/watch?v=NtjyeojAOBs). +In Jest 21 we introduced the concept of custom Jest runners. Since then, Rogelio, one of Jest's core contributors, built a number of useful runners: If you have many existing tests written using another framework but you'd like to immediately benefit from Jest's features, check out [jest-runner-mocha](https://yarnpkg.com/en/package/jest-runner-mocha). If you have a large codebase that needs linting, [you may get a significant speedup](https://twitter.com/lencioni/status/907398856756695040) if you run eslint within Jest using [jest-runner-eslint](https://yarnpkg.com/en/package/jest-runner-eslint). + +To gain more of fine-grained control over heavy tasks parallelization (e.g. transforming files or crawling the file system), we designed a new library perfectly suited for the job. We developed a modern, Promise-based module with an approachable API, called `jest-worker`, that allows you to delegate to child processes those intensive functions. As `jest-worker`, like any other Jest package, is a part of the Jest platform, you can use it however you like even without ever using Jest itself. You'll find more in the documentation [here](https://yarnpkg.com/en/package/jest-worker). + +To get a better understanding of custom runners and Jest as a platform, make sure to check out Rogelio's talk from Reactive Conf 2017: [Jest as a Platform](https://www.youtube.com/watch?v=NtjyeojAOBs). ## Codeframe in test failures -In order to more easily identify which assertion is failing your test, we've -added a code frame showing the context where the assertion is in order to focus -on your own code. See the following example test: +In order to more easily identify which assertion is failing your test, we've added a code frame showing the context where the assertion is in order to focus on your own code. See the following example test: ``` test('some test', () => { @@ -71,16 +41,13 @@ In Jest 21, we would display the following error: ![failure in Jest 21](/jest/img/blog/22-failure-21.png) -In Jest 22, we have added a codeframe, giving more context to the failing -assertions. We have also cleaned up the stack trace to remove more clutter than -ever. +In Jest 22, we have added a codeframe, giving more context to the failing assertions. We have also cleaned up the stack trace to remove more clutter than ever. ![failure in Jest 22](/jest/img/blog/22-failure-22.png) ## Easier testing of errors thrown in async code -You can now use `toThrow` and `toThrowErrorMatchingSnapshot` on promise -rejections in the same way you can on synchronous errors. +You can now use `toThrow` and `toThrowErrorMatchingSnapshot` on promise rejections in the same way you can on synchronous errors. ``` async function throwingFunction() { @@ -94,56 +61,23 @@ test('asynchronous rejection', async () => { ## Asynchronous test environments -When [Puppeteer](https://github.com/GoogleChrome/puppeteer/), a way of -programmatically interacting with a real Chromium Browser, was announced by the -Google Chrome team in August, many wanted to be able to use Jest to write their -tests running them in Chrome. The community have helped us out making this -possible by allowing asynchronous test environments. We are still working on -making this experience as good as possible, but please see -[this guide](http://facebook.github.io/jest/docs/en/puppeteer.html) for how to -use Puppeteer with Jest, starting today. +When [Puppeteer](https://github.com/GoogleChrome/puppeteer/), a way of programmatically interacting with a real Chromium Browser, was announced by the Google Chrome team in August, many wanted to be able to use Jest to write their tests running them in Chrome. The community have helped us out making this possible by allowing asynchronous test environments. We are still working on making this experience as good as possible, but please see [this guide](http://facebook.github.io/jest/docs/en/puppeteer.html) for how to use Puppeteer with Jest, starting today. ## Experimental Leak Detection -We added an experimental `--detectLeaks` setting to Jest that will let you know -if your internal environment instance is leaked after a test execution. It will -also warn you when your test suite tries to require a file after the test has -finished, meaning you forgot to wait for all async operations or left something -not properly cleaned. This will however not discover leaks in user land code, -only in test land code; although the technology used behind it can help you (see -`jest-leak-detector`). If you are reporting a bug about Jest's memory usage, -please provide a repro where `--detectLeaks` will make the test suite fail. We -[started building a better sandboxing mechanism](https://github.com/facebook/jest/pull/4970) -for Jest but it's not ready yet to be enabled by default. If you'd like to help, -please reach out to us on discord! +We added an experimental `--detectLeaks` setting to Jest that will let you know if your internal environment instance is leaked after a test execution. It will also warn you when your test suite tries to require a file after the test has finished, meaning you forgot to wait for all async operations or left something not properly cleaned. This will however not discover leaks in user land code, only in test land code; although the technology used behind it can help you (see `jest-leak-detector`). If you are reporting a bug about Jest's memory usage, please provide a repro where `--detectLeaks` will make the test suite fail. We [started building a better sandboxing mechanism](https://github.com/facebook/jest/pull/4970) for Jest but it's not ready yet to be enabled by default. If you'd like to help, please reach out to us on discord! ## Watch Mode Refinements -When using watch mode, there is now a way to -[focus only on tests that previously failed](https://github.com/facebook/jest/pull/4886). -In this mode, Jest will not re-run previously passing tests which should help -you iron out all test failures. Additionally, -[we added a plugin system to watch mode](https://github.com/facebook/jest/pull/4841). -By adding modules to `watchPlugins` in your configuration you can extend the -features of the watch mode. +When using watch mode, there is now a way to [focus only on tests that previously failed](https://github.com/facebook/jest/pull/4886). In this mode, Jest will not re-run previously passing tests which should help you iron out all test failures. Additionally, [we added a plugin system to watch mode](https://github.com/facebook/jest/pull/4841). By adding modules to `watchPlugins` in your configuration you can extend the features of the watch mode. ## Babel 7 support -Jest uses Babel under the hood to power code coverage and advanced mocking -features. With Jest 22, it also supports the upcoming Babel 7. You'll find more -in the documentation -[here](http://facebook.github.io/jest/docs/en/getting-started.html#using-babel). +Jest uses Babel under the hood to power code coverage and advanced mocking features. With Jest 22, it also supports the upcoming Babel 7. You'll find more in the documentation [here](http://facebook.github.io/jest/docs/en/getting-started.html#using-babel). ## Mock function improvements -There has been a couple of changes to mock functions in Jest 22, making them -even easier to use. Firstly, we added a -[`mockName`](http://facebook.github.io/jest/docs/en/mock-function-api.html#mockfnmocknamevalue) -property allowing you to name your mocks, which is useful in assertion failures. -We have also made the Jest mock function serializable in `pretty-format`, -meaning that you can snapshot test mocks. In Jest 21, -`expect(jest.fn()).toMatchSnapshot()` would serialize to `[Function]`, in Jest -22, you might get something like this: +There has been a couple of changes to mock functions in Jest 22, making them even easier to use. Firstly, we added a [`mockName`](http://facebook.github.io/jest/docs/en/mock-function-api.html#mockfnmocknamevalue) property allowing you to name your mocks, which is useful in assertion failures. We have also made the Jest mock function serializable in `pretty-format`, meaning that you can snapshot test mocks. In Jest 21, `expect(jest.fn()).toMatchSnapshot()` would serialize to `[Function]`, in Jest 22, you might get something like this: ``` test('my mocking test', () => { @@ -170,66 +104,26 @@ test('my mocking test', () => { ## Highlights from Jest 21 -Jest 21 was released back in September, and we unfortunately never got around to -write a blog post. So here is a quick summary of the main changes in version 21: - -1. **Use expect and jest-mock in the browser:** - [Michael Jackson](https://github.com/mjackson) donated his excellent - [`expect`](https://github.com/mjackson/expect) package to the Jest project. - As part of that transition, the Jest core team, with much help from - [Kenneth Skovhus](https://github.com/skovhus/), made both `jest-matchers` - (renamed to `expect`) and `jest-mock` work in browsers. This means that - while you cannot use Jest itself in browsers - ([yet](https://github.com/facebook/jest/issues/848)), you can use its - awesome assertions and mocks for instance as replacements for Chai and Sinon - running in Mocha tests. If you are migrating from earlier `expect` to the - new Jest-powered `expect`, you can use - [`jest-codemods`](https://github.com/skovhus/jest-codemods/) to automate the - migration. +Jest 21 was released back in September, and we unfortunately never got around to write a blog post. So here is a quick summary of the main changes in version 21: + +1. **Use expect and jest-mock in the browser:** [Michael Jackson](https://github.com/mjackson) donated his excellent [`expect`](https://github.com/mjackson/expect) package to the Jest project. As part of that transition, the Jest core team, with much help from [Kenneth Skovhus](https://github.com/skovhus/), made both `jest-matchers` (renamed to `expect`) and `jest-mock` work in browsers. This means that while you cannot use Jest itself in browsers ([yet](https://github.com/facebook/jest/issues/848)), you can use its awesome assertions and mocks for instance as replacements for Chai and Sinon running in Mocha tests. If you are migrating from earlier `expect` to the new Jest-powered `expect`, you can use [`jest-codemods`](https://github.com/skovhus/jest-codemods/) to automate the migration. 2. **MIT License:** We changed Jest's license to MIT. _Yay!_ -3. **Fail test suites on async errors:** Jest used to have a bug that made it - crash when errors were thrown in certain parts of async code. This was fixed - by community contributors. -4. **Faster startup:** With Jest 21 we fine tuned Jest's startup to be more - than 50% faster. The large overhead of Jest when running it on a small and - fast test was always an issue for us and now this shouldn't be a reason to - hold you back from using Jest any longer. +3. **Fail test suites on async errors:** Jest used to have a bug that made it crash when errors were thrown in certain parts of async code. This was fixed by community contributors. +4. **Faster startup:** With Jest 21 we fine tuned Jest's startup to be more than 50% faster. The large overhead of Jest when running it on a small and fast test was always an issue for us and now this shouldn't be a reason to hold you back from using Jest any longer. ## Jest Community -The community around Jest is working hard to make the testing experience even -greater. These are separate projects from the main Jest project, but we want to -highlight some of our personal favorites here. - -* [jest-image-snapshot](https://github.com/americanexpress/jest-image-snapshot) - – custom matcher to compare images with snapshots by American Express - developers -* [ts-jest](https://github.com/kulshekhar/ts-jest) – all you need to - successfully run Jest within TypeScript project by - [@kulshekhar](https://github.com/kulshekhar/ts-jest) -* [jest-codemods](https://github.com/skovhus/jest-codemods/) – migrate your - tests from other frameworks to Jest with ease -* [jest-plugins](https://github.com/negativetwelve/jest-plugins) – a new - community project oriented around simplifying setting up test environment for - specific tools, like React, or providing some handy utilities - -We'd also like to announce that recently we launched a new place for high -quality Jest additions – [jest-community](https://github.com/jest-community). -It's a new GitHub organization already featuring our favorite projects, like -[vscode-jest](https://github.com/jest-community/vscode-jest), -[jest-extended](https://github.com/jest-community/jest-extended), to name a few, -curated by Jest maintainers and collaborators. We've even migrated our -[eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) -there, and already see some great contributions, which are published -independently at a faster pace. +The community around Jest is working hard to make the testing experience even greater. These are separate projects from the main Jest project, but we want to highlight some of our personal favorites here. + +* [jest-image-snapshot](https://github.com/americanexpress/jest-image-snapshot) – custom matcher to compare images with snapshots by American Express developers +* [ts-jest](https://github.com/kulshekhar/ts-jest) – all you need to successfully run Jest within TypeScript project by [@kulshekhar](https://github.com/kulshekhar/ts-jest) +* [jest-codemods](https://github.com/skovhus/jest-codemods/) – migrate your tests from other frameworks to Jest with ease +* [jest-plugins](https://github.com/negativetwelve/jest-plugins) – a new community project oriented around simplifying setting up test environment for specific tools, like React, or providing some handy utilities + +We'd also like to announce that recently we launched a new place for high quality Jest additions – [jest-community](https://github.com/jest-community). It's a new GitHub organization already featuring our favorite projects, like [vscode-jest](https://github.com/jest-community/vscode-jest), [jest-extended](https://github.com/jest-community/jest-extended), to name a few, curated by Jest maintainers and collaborators. We've even migrated our [eslint-plugin-jest](https://github.com/jest-community/eslint-plugin-jest) there, and already see some great contributions, which are published independently at a faster pace. ![Jest Community](/jest/img/blog/22-community.png) -Community projects under one organisation are also a great way for us to -experiment on things like automated releases, which we'd like to explore for -Jest as well. They also enable us to share some common things between them, like -the shape of the README for example (thanks to the webpack Community for the -idea), making it easier to learn and use for all of us. +Community projects under one organisation are also a great way for us to experiment on things like automated releases, which we'd like to explore for Jest as well. They also enable us to share some common things between them, like the shape of the README for example (thanks to the webpack Community for the idea), making it easier to learn and use for all of us. -If you have something awesome to share, feel free to reach out to us! We'd love -to share your project here. +If you have something awesome to share, feel free to reach out to us! We'd love to share your project here. diff --git a/website/versioned_docs/version-22.0/CLI.md b/website/versioned_docs/version-22.0/CLI.md index 8531ff722ab3..25b51d536005 100644 --- a/website/versioned_docs/version-22.0/CLI.md +++ b/website/versioned_docs/version-22.0/CLI.md @@ -4,10 +4,7 @@ title: Jest CLI Options original_id: 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. +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: @@ -38,8 +35,7 @@ Run tests related to `path/to/fileA.js` and `path/to/fileB.js`: 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 @@ -52,13 +48,11 @@ 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" @@ -70,8 +64,7 @@ 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 @@ -83,11 +76,7 @@ CLI options take precedence over values from the ### `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` @@ -95,39 +84,27 @@ 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`. ### `--changedFilesWithAncestor` -When used together with `--onlyChanged` or `--watch`, it runs tests related to -the current changes and the changes made in the last commit. +When used together with `--onlyChanged` or `--watch`, it runs tests related to the current changes and the changes made in the last commit. ### `--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` ##### available in Jest **22.0.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` @@ -135,15 +112,11 @@ 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` @@ -151,8 +124,7 @@ 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` @@ -160,18 +132,11 @@ 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` @@ -179,8 +144,7 @@ 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=` @@ -188,26 +152,19 @@ Write test results to a file when the `--json` option is also specified. ### `--lastCommit` -When used together with `--onlyChanged`, it will run all tests affected by file -changes in the last commit made. +When used together with `--onlyChanged`, it 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` @@ -215,15 +172,11 @@ 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). ### `--passWithNoTests` @@ -235,15 +188,11 @@ 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` @@ -255,15 +204,11 @@ 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. @@ -276,8 +221,7 @@ Note that `column` is 0-indexed while `line` is not. ### `--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=` @@ -285,9 +229,7 @@ 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` @@ -303,16 +245,12 @@ 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/website/versioned_docs/version-22.0/Configuration.md b/website/versioned_docs/version-22.0/Configuration.md index 35f40dc0768b..1508cc908654 100644 --- a/website/versioned_docs/version-22.0/Configuration.md +++ b/website/versioned_docs/version-22.0/Configuration.md @@ -4,11 +4,7 @@ title: Configuring Jest original_id: configuration --- -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 { @@ -41,9 +37,7 @@ 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. @@ -55,34 +49,23 @@ configuration power. 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] @@ -90,27 +73,19 @@ 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. +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. Example: @@ -124,11 +99,9 @@ Example: } ``` -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] @@ -140,42 +113,25 @@ The directory where Jest should output its coverage files. 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. Thresholds can be specified as `global`, as a -[glob](https://github.com/isaacs/node-glob#glob-primer), and as a directory or -file path. If thresholds aren't met, jest will fail. Thresholds specified as a -positive number are taken to be the minimum percentage required. Thresholds -specified as a negative number represent the maximum number of uncovered -entities allowed. +This will be used to configure minimum threshold enforcement for coverage results. Thresholds can be specified as `global`, as a [glob](https://github.com/isaacs/node-glob#glob-primer), and as a directory or file path. If thresholds aren't met, jest will fail. Thresholds specified as a positive number are taken to be the minimum percentage required. Thresholds specified as a negative number represent the maximum number of uncovered entities allowed. -For example, with the following configuration jest will fail if there is less -than 80% branch, line, and function coverage, or if there are more than 10 -uncovered statements: +For example, with the following configuration jest will fail if there is less than 80% branch, line, and function coverage, or if there are more than 10 uncovered statements: ```json { @@ -193,10 +149,7 @@ uncovered statements: } ``` -If globs or paths are specified alongside `global`, coverage data for matching -paths will be subtracted from overall coverage and thresholds will be applied -independently. Thresholds for globs are applied to all files matching the glob. -If the file specified by path is not found, error is returned. +If globs or paths are specified alongside `global`, coverage data for matching paths will be subtracted from overall coverage and thresholds will be applied independently. Thresholds for globs are applied to all files matching the glob. If the file specified by path is not found, error is returned. For example, with the following configuration: @@ -231,10 +184,8 @@ For example, with the following configuration: Jest will fail if: -* The `./src/components` directory has less than 40% branch or statement - coverage. -* One of the files matching the `./src/reducers/**/*.js` glob has less than 90% - statement coverage. +* The `./src/components` directory has less than 40% branch or statement coverage. +* One of the files matching the `./src/reducers/**/*.js` glob has less than 90% statement coverage. * The `./src/api/very-important-module.js` file has less than 100% coverage. * Every remaining file combined has less than 50% coverage (`global`). @@ -242,12 +193,9 @@ Jest will fail if: Default: `['']` -Test files are normally ignored from collecting code coverage. With this option, -you can overwrite this behavior and include otherwise ignored files in code -coverage. +Test files are normally ignored from collecting code coverage. With this option, you can overwrite this behavior and include otherwise ignored files in code coverage. -For example, if you have tests in source files named with `.t.js` extension as -following: +For example, if you have tests in source files named with `.t.js` extension as following: ```javascript // sum.t.js @@ -280,8 +228,7 @@ 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 { @@ -294,23 +241,19 @@ For example, the following would create a global `__DEV__` variable set to } ``` -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. ### `globalSetup` [string] Default: `undefined` -This option allows the use of a custom global setup module which exports an -async function that is triggered once before all test suites. +This option allows the use of a custom global setup module which exports an async function that is triggered once before all test suites. ### `globalTeardown` [string] Default: `undefined` -This option allows the use of a custom global teardown module which exports an -async function that is triggered once after all test suites. +This option allows the use of a custom global teardown module which exports an async function that is triggered once after all test suites. ### `mapCoverage` [boolean] @@ -318,20 +261,9 @@ async function that is triggered once after all test suites. 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 { @@ -344,36 +276,27 @@ return { 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: @@ -387,36 +310,23 @@ Example: } ``` -The order in which the mappings are defined matters. Patterns are checked one by -one until one fits. The most specific rule should be listed first. +The order in which the mappings are defined matters. Patterns are checked one by one until one fits. The most specific rule should be listed first. -_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] @@ -428,17 +338,13 @@ Activates notifications for test results. 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 { @@ -446,15 +352,9 @@ time. } ``` -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. -The projects feature can also be used to run multiple configurations or multiple -[runners](#runner-string). For this purpose you can pass an array of -configuration objects. For example, to run both tests and ESLint (via -[jest-runner-eslint](https://github.com/jest-community/jest-runner-eslint)) in -the same invocation of Jest: +The projects feature can also be used to run multiple configurations or multiple [runners](#runner-string). For this purpose you can pass an array of configuration objects. For example, to run both tests and ESLint (via [jest-runner-eslint](https://github.com/jest-community/jest-runner-eslint)) in the same invocation of Jest: ```json { @@ -475,9 +375,7 @@ the same invocation of Jest: 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] @@ -485,12 +383,9 @@ 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: @@ -500,8 +395,7 @@ This will override default reporters: } ``` -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 { @@ -509,8 +403,7 @@ provides: } ``` -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 { @@ -521,8 +414,7 @@ as a second argument: } ``` -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: @@ -544,8 +436,7 @@ 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 { @@ -558,26 +449,19 @@ 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] @@ -585,10 +469,7 @@ 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: ``` { @@ -601,28 +482,17 @@ argument: } ``` -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 +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`. +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] @@ -630,19 +500,11 @@ 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/"]`._ ### `runner` [string] @@ -650,16 +512,14 @@ where you may want to have multiple roots within one project, for example Default: `"jest-runner"` -This option allows you to use a custom runner instead of Jest's default test -runner. Examples of runners include: +This option allows you to use a custom runner instead of Jest's default test runner. Examples of runners include: * [`jest-runner-eslint`](https://github.com/jest-community/jest-runner-eslint) * [`jest-runner-mocha`](https://github.com/rogeliog/jest-runner-mocha) * [`jest-runner-tsc`](https://github.com/azz/jest-runner-tsc) * [`jest-runner-prettier`](https://github.com/keplersj/jest-runner-prettier) -To write a test-runner, export a class with which accepts `globalConfig` in the -constructor, and has a `runTests` method with the signature: +To write a test-runner, export a class with which accepts `globalConfig` in the constructor, and has a `runTests` method with the signature: ```ts async runTests( @@ -676,40 +536,25 @@ async runTests( 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. +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: @@ -728,8 +573,7 @@ module.exports = { `serialize` is a function that serializes a value using existing plugins. -To use `my-serializer-module` as a serializer, configuration would be as -follows: +To use `my-serializer-module` as a serializer, configuration would be as follows: ```json { @@ -764,22 +608,15 @@ 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+** @@ -794,16 +631,11 @@ test('use jsdom in this test file', () => { }); ``` -You can create your own module that will be used for setting up the test -environment. The module must export a class with `setup`, `teardown` and -`runScript` methods. You can also pass variables from this module to your test -suites by assigning them to `this.global` object – this will make them -available in your test suites as global variables. +You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables. ##### available in Jest **22.0.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: @@ -849,10 +681,7 @@ beforeAll(() => { Default: `{}` -Test environment options that will be passed to the `testEnvironment`. The -relevant options depend on the environment. For example you can override options -given to [jsdom](https://github.com/tmpvar/jsdom) such as -`{userAgent: "Agent/007"}`. +Test environment options that will be passed to the `testEnvironment`. The relevant options depend on the environment. For example you can override options given to [jsdom](https://github.com/tmpvar/jsdom) such as `{userAgent: "Agent/007"}`. ### `testMatch` [array] @@ -860,41 +689,25 @@ given to [jsdom](https://github.com/tmpvar/jsdom) such as (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: @@ -912,9 +725,7 @@ The following is a visualization of the default regex: 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: ``` { @@ -961,9 +772,7 @@ structure as the first argument and return it: 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: @@ -976,100 +785,59 @@ 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` 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)_ +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` 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. +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/"]`. -Sometimes it happens (especially in React Native or TypeScript projects) that -3rd party modules are published as untranspiled. Since all files inside -`node_modules` are not transformed by default, Jest will not understand the code -in these modules, resulting in syntax errors. To overcome this, you may use -`transformIgnorePatterns` to whitelist such modules. You'll find a good example -of this use case in -[React Native Guide](http://facebook.github.io/jest/docs/en/tutorial-react-native.html#transformignorepatterns-customization). +Sometimes it happens (especially in React Native or TypeScript projects) that 3rd party modules are published as untranspiled. Since all files inside `node_modules` are not transformed by default, Jest will not understand the code in these modules, resulting in syntax errors. To overcome this, you may use `transformIgnorePatterns` to whitelist such modules. You'll find a good example of this use case in [React Native Guide](http://facebook.github.io/jest/docs/en/tutorial-react-native.html#transformignorepatterns-customization). ### `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] @@ -1077,11 +845,6 @@ 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/website/versioned_docs/version-22.0/ExpectAPI.md b/website/versioned_docs/version-22.0/ExpectAPI.md index 5554f2e23551..9e4025fbc642 100644 --- a/website/versioned_docs/version-22.0/ExpectAPI.md +++ b/website/versioned_docs/version-22.0/ExpectAPI.md @@ -4,9 +4,7 @@ title: Expect original_id: 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 @@ -18,13 +16,9 @@ validate different things. ### `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'`. -Here's how you would test that: +It's easier to understand this with an example. Let's say you have a method `bestLaCroixFlavor()` which is supposed to return the string `'grapefruit'`. Here's how you would test that: ```js test('the best flavor is grapefruit', () => { @@ -32,20 +26,13 @@ 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({ @@ -72,34 +59,23 @@ 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'); @@ -146,16 +122,11 @@ 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', () => { @@ -167,10 +138,7 @@ 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) { @@ -186,10 +154,7 @@ 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: @@ -226,13 +191,9 @@ describe('Beware of a misunderstanding! A sequence of dice rolls', () => { ### `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', () => { @@ -252,14 +213,9 @@ 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', () => { @@ -271,22 +227,15 @@ 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', () => { @@ -305,13 +254,11 @@ 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: @@ -319,8 +266,7 @@ 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', () => { @@ -343,13 +289,9 @@ describe('stringMatching in arrayContaining', () => { ### `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'; @@ -358,20 +300,16 @@ 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', () => { @@ -383,11 +321,9 @@ 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', () => { @@ -396,9 +332,7 @@ test('resolves to lemon', () => { }); ``` -Note that, since you are still testing promises, the test is still asynchronous. -Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by -returning the unwrapped assertion. +Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. Alternatively, you can use `async/await` in combination with `.resolves`: @@ -413,8 +347,7 @@ 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'`: @@ -427,9 +360,7 @@ test('rejects to octopus', () => { }); ``` -Note that, since you are still testing promises, the test is still asynchronous. -Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by -returning the unwrapped assertion. +Note that, since you are still testing promises, the test is still asynchronous. Hence, you will need to [tell Jest to wait](TestingAsyncCode.md#promises) by returning the unwrapped assertion. Alternatively, you can use `async/await` in combination with `.rejects`. @@ -441,8 +372,7 @@ test('rejects to octopus', async () => { ### `.toBe(value)` -`toBe` just checks that a value is what you expect. It uses `Object.is` to check -exact equality. +`toBe` just checks that a value is what you expect. It uses `Object.is` to check exact equality. For example, this code will validate some properties of the `can` object: @@ -463,9 +393,7 @@ 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()` @@ -473,11 +401,7 @@ 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', () => { @@ -497,13 +421,9 @@ 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', () => { @@ -517,12 +437,9 @@ 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', () => { @@ -538,11 +455,7 @@ 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', () => { @@ -554,8 +467,7 @@ 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', () => { @@ -563,12 +475,9 @@ 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', () => { @@ -576,14 +485,11 @@ 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', () => { @@ -591,14 +497,11 @@ 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(); @@ -607,9 +510,7 @@ 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', () => { @@ -618,14 +519,11 @@ 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', () => { @@ -635,9 +533,7 @@ 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', () => { @@ -647,9 +543,7 @@ 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', () => { @@ -659,9 +553,7 @@ 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', () => { @@ -671,8 +563,7 @@ 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 {} @@ -684,8 +575,7 @@ 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() { @@ -699,9 +589,7 @@ 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(); @@ -710,10 +598,7 @@ 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', () => { @@ -722,14 +607,11 @@ 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', () => { @@ -737,17 +619,13 @@ 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', () => { @@ -757,10 +635,7 @@ 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', () => { @@ -773,10 +648,7 @@ 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 = { @@ -798,14 +670,11 @@ 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. @@ -819,9 +688,7 @@ 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', () => { @@ -844,16 +711,9 @@ 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. @@ -903,19 +763,11 @@ 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 you may -use -[dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) -or an array containing the keyPath for deep references. +Use `.toHaveProperty` to check if property at provided reference `keyPath` exists for an object. For checking deeply nested properties in an object you may use [dot notation](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Property_accessors) or an array containing the keyPath for deep references. -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 @@ -960,22 +812,17 @@ 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', () => { @@ -985,10 +832,7 @@ 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 that should be contained in -the error message, a class for the error, or a regex that should match the error -message. 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 that should be contained in the error message, a class for the error, or a regex that should match the error message. For example, let's say that `drinkFlavor` is coded like this: ```js function drinkFlavor(flavor) { @@ -1019,15 +863,11 @@ 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) { @@ -1056,6 +896,4 @@ 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/website/versioned_docs/version-22.0/GettingStarted.md b/website/versioned_docs/version-22.0/GettingStarted.md index 231f29a52fa0..bd7cce4116d9 100644 --- a/website/versioned_docs/version-22.0/GettingStarted.md +++ b/website/versioned_docs/version-22.0/GettingStarted.md @@ -16,8 +16,7 @@ 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) { @@ -55,51 +54,39 @@ 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 babel-core regenerator-runtime ``` -> Note: If you are using a babel version 7 then you need to install `babel-jest` -> with the following command: +> Note: If you are using a babel version 7 then you need to install `babel-jest` with the following command: > > ``` > npm install --save-dev babel-jest 'babel-core@^7.0.0-0' @babel/core 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 { @@ -109,14 +96,9 @@ in your project's root folder. For example, if you are using ES6 and 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 { @@ -129,10 +111,7 @@ You are now set up to use all ES6 features and React specific syntax. } ``` -> 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 @@ -145,12 +124,8 @@ You are now set up to use all ES6 features and React specific syntax. ### 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/website/versioned_docs/version-22.0/GlobalAPI.md b/website/versioned_docs/version-22.0/GlobalAPI.md index a863b53d8534..5e0cd868a7b6 100644 --- a/website/versioned_docs/version-22.0/GlobalAPI.md +++ b/website/versioned_docs/version-22.0/GlobalAPI.md @@ -4,8 +4,7 @@ title: Globals original_id: api --- -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 @@ -17,15 +16,11 @@ environment. You don't have to require or import anything to use them. ### `afterAll(fn, timeout)` -Runs a function after all the tests in this file have completed. If the function -returns a promise or is a generator, Jest waits for that promise to resolve -before continuing. +Runs a function after all the tests in this file have completed. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to clean up some global setup state that is -shared across tests. +This is often useful if you want to clean up some global setup state that is shared across tests. For example: @@ -53,26 +48,19 @@ 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, timeout)` -Runs a function after each one of the tests in this file completes. If the -function returns a promise or is a generator, Jest waits for that promise to -resolve before continuing. +Runs a function after each one of the tests in this file completes. If the function returns a promise or is a generator, Jest waits for that promise to resolve before continuing. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to clean up some temporary state that is -created by each test. +This is often useful if you want to clean up some temporary state that is created by each test. For example: @@ -100,26 +88,19 @@ 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, timeout)` -Runs a function before any of the tests in this file run. If the function -returns a promise or is a generator, Jest waits for that promise to resolve -before running tests. +Runs a function before any of the tests in this file run. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running tests. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to set up some global state that will be used -by many tests. +This is often useful if you want to set up some global state that will be used by many tests. For example: @@ -143,28 +124,19 @@ 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, timeout)` -Runs a function before each of the tests in this file runs. If the function -returns a promise or is a generator, Jest waits for that promise to resolve -before running the test. +Runs a function before each of the tests in this file runs. If the function returns a promise or is a generator, Jest waits for that promise to resolve before running the test. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -This is often useful if you want to reset some global state that will be used by -many tests. +This is often useful if you want to reset some global state that will be used by many tests. For example: @@ -194,17 +166,13 @@ 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 = { @@ -223,9 +191,7 @@ 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: @@ -283,8 +249,7 @@ 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', () => { @@ -302,26 +267,21 @@ 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)` -Returns the actual module instead of a mock, bypassing all checks on whether the -module should receive a mock implementation or not. +Returns the actual module instead of a mock, bypassing all checks on whether the module should receive a mock implementation or not. ### `require.requireMock(moduleName)` -Returns a mock module instead of the actual module, bypassing all checks on -whether the module should be required normally or not. +Returns a mock module instead of the actual module, bypassing all checks on whether the module should be required normally or not. ### `test(name, fn, timeout)` Also under the alias: `it(name, fn, timeout)` -All you need in a test file is the `test` method which runs a test. For example, -let's say there's a function `inchesOfRain()` that should be zero. Your whole -test could be: +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', () => { @@ -329,19 +289,11 @@ test('did not rain', () => { }); ``` -The first argument is the test name; the second argument is a function that -contains the expectations to test. The third argument (optional) is `timeout` -(in milliseconds) for specifying how long to wait before aborting. _Note: The -default timeout is 5 seconds._ +The first argument is the test name; the second argument is a function that contains the expectations to test. The third argument (optional) is `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ -> 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', () => { @@ -351,19 +303,15 @@ 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, timeout)` Also under the aliases: `it.only(name, fn, timeout)` or `fit(name, fn, timeout)` -When you are debugging a large test file, you will often only want to run a -subset of tests. You can use `.only` to specify which tests are the only ones -you want to run in that test file. +When you are debugging a large test file, you will often only want to run a subset of tests. You can use `.only` to specify which tests are the only ones you want to run in that test file. -Optionally, you can provide a `timeout` (in milliseconds) for specifying how -long to wait before aborting. _Note: The default timeout is 5 seconds._ +Optionally, you can provide a `timeout` (in milliseconds) for specifying how long to wait before aborting. _Note: The default timeout is 5 seconds._ For example, let's say you had these tests: @@ -377,22 +325,15 @@ test('it is not snowing', () => { }); ``` -Only the "it is raining" test will run in that test file, since it is run with -`test.only`. +Only the "it is raining" test will run in that test file, since it is run with `test.only`. -Usually you wouldn't check code using `test.only` into source control - you -would use it 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: @@ -406,8 +347,6 @@ 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/website/versioned_docs/version-22.0/JestObjectAPI.md b/website/versioned_docs/version-22.0/JestObjectAPI.md index 2d9a4050239d..ce941b7e1f71 100644 --- a/website/versioned_docs/version-22.0/JestObjectAPI.md +++ b/website/versioned_docs/version-22.0/JestObjectAPI.md @@ -4,9 +4,7 @@ title: The Jest Object original_id: 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 @@ -42,32 +40,21 @@ behavior. 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()` @@ -75,14 +62,11 @@ 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(); @@ -100,16 +84,13 @@ 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. +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. +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 @@ -123,8 +104,7 @@ 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', () => { @@ -136,8 +116,7 @@ const moduleName = require('../moduleName'); 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( @@ -152,35 +131,25 @@ jest.mock( ); ``` -_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). +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). +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. +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: +One example when this is useful is when you want to mock a module differently within the same file: ```js beforeEach(() => { @@ -208,23 +177,19 @@ 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. @@ -232,15 +197,11 @@ Returns the `jest` object for chaining. ##### 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: @@ -273,28 +234,17 @@ Returns the `jest` object for chaining. ### `jest.runAllTicks()` -Exhausts the **micro**-task queue (usually interfaced in node via -`process.nextTick`). +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. +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()`). +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. +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()` @@ -306,55 +256,31 @@ Exhausts all tasks queued by `setImmediate()`. 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. +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. +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. +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. +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. +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._ @@ -366,9 +292,7 @@ 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. @@ -382,14 +306,9 @@ Returns the `jest` object for chaining. ##### 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. +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);`_ +_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: @@ -424,9 +343,7 @@ test('plays video', () => { ##### available in Jest **22.1.0+** -Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of -`accessType` that can be either `'get'` or `'set'`, which proves to be useful -when you want to spy on a getter or a setter, respectively. +Since Jest 22.1.0+, the `jest.spyOn` method takes an optional third argument of `accessType` that can be either `'get'` or `'set'`, which proves to be useful when you want to spy on a getter or a setter, respectively. Example: diff --git a/website/versioned_docs/version-22.0/JestPlatform.md b/website/versioned_docs/version-22.0/JestPlatform.md index 438f732f1c2d..fa2f898a2b9d 100644 --- a/website/versioned_docs/version-22.0/JestPlatform.md +++ b/website/versioned_docs/version-22.0/JestPlatform.md @@ -4,18 +4,14 @@ title: Jest Platform original_id: jest-platform --- -You can cherry pick specific features of Jest and use them as standalone -packages. Here's a list of the available packages: +You can cherry pick specific features of Jest and use them as standalone packages. Here's a list of the available packages: ## jest-changed-files -Tool for identifying modified files in a git/hg repository. Exports two -functions: +Tool for identifying modified files in a git/hg repository. Exports two functions: -* `getChangedFilesForRoots` returns a promise that resolves to an object with - the changed files and repos. -* `findRepos` returns a promise that resolves to a set of repositories contained - in the specified path. +* `getChangedFilesForRoots` returns a promise that resolves to an object with the changed files and repos. +* `findRepos` returns a promise that resolves to a set of repositories contained in the specified path. ### Example @@ -28,14 +24,11 @@ getChangedFilesForRoots(['./'], { }).then(result => console.log(result.changedFiles)); ``` -You can read more about `jest-changed-files` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-changed-files/README.md). +You can read more about `jest-changed-files` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-changed-files/README.md). ## jest-diff -Tool for visualizing changes in data. Exports a function that compares two -values of any type and returns a "pretty-printed" string illustrating the -difference between the two arguments. +Tool for visualizing changes in data. Exports a function that compares two values of any type and returns a "pretty-printed" string illustrating the difference between the two arguments. ### Example @@ -53,8 +46,7 @@ console.log(result); ## jest-docblock -Tool for extracting and parsing the comments at the top of a JavaScript file. -Exports various function to manipulate the data inside the comment block. +Tool for extracting and parsing the comments at the top of a JavaScript file. Exports various function to manipulate the data inside the comment block. ### Example @@ -77,13 +69,11 @@ const parsed = parseWithComments(code); console.log(parsed); ``` -You can read more about `jest-docblock` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-docblock/README.md). +You can read more about `jest-docblock` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-docblock/README.md). ## jest-get-type -Module that identifies the primitive type of any JavaScript value. Exports a -function that returns a string with the type of the value passed as argument. +Module that identifies the primitive type of any JavaScript value. Exports a function that returns a string with the type of the value passed as argument. ### Example @@ -104,13 +94,9 @@ console.log(getType(undefinedValue)); ## jest-validate -Tool for validating configurations submitted by users. Exports a function that -takes two arguments: the user's configuration and an object containing an -example configuration and other options. The return value is an object with two -attributes: +Tool for validating configurations submitted by users. Exports a function that takes two arguments: the user's configuration and an object containing an example configuration and other options. The return value is an object with two attributes: -* `hasDeprecationWarnings`, a boolean indicating whether the submitted - configuration has deprecation warnings, +* `hasDeprecationWarnings`, a boolean indicating whether the submitted configuration has deprecation warnings, * `isValid`, a boolean indicating whether the configuration is correct or not. ### Example @@ -130,15 +116,11 @@ const result = validate(configByUser, { console.log(result); ``` -You can read more about `jest-validate` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-validate/README.md). +You can read more about `jest-validate` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-validate/README.md). ## jest-worker -Module used for parallelization of tasks. Exports a class `Worker` that takes -the path of Node.js module and lets you call the module's exported methods as if -they where class methods, returning a promise that resolves when the specified -method finishes its execution in a forked process. +Module used for parallelization of tasks. Exports a class `Worker` that takes the path of Node.js module and lets you call the module's exported methods as if they where class methods, returning a promise that resolves when the specified method finishes its execution in a forked process. ### Example @@ -170,14 +152,11 @@ async function main() { main(); ``` -You can read more about `jest-worker` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/jest-worker/README.md). +You can read more about `jest-worker` in the [readme file](https://github.com/facebook/jest/blob/master/packages/jest-worker/README.md). ## pretty-format -Exports a function that converts any JavaScript value into a human-readable -string. Supports all built-in JavaScript types out of the box and allows -extension for application-specific types via user-defined plugins. +Exports a function that converts any JavaScript value into a human-readable string. Supports all built-in JavaScript types out of the box and allows extension for application-specific types via user-defined plugins. ### Example @@ -193,5 +172,4 @@ val.array = [-0, Infinity, NaN]; console.log(prettyFormat(val)); ``` -You can read more about `pretty-format` in the -[readme file](https://github.com/facebook/jest/blob/master/packages/pretty-format/README.md). +You can read more about `pretty-format` in the [readme file](https://github.com/facebook/jest/blob/master/packages/pretty-format/README.md). diff --git a/website/versioned_docs/version-22.0/ManualMocks.md b/website/versioned_docs/version-22.0/ManualMocks.md index 4c8f02937a8c..750eb3624b36 100644 --- a/website/versioned_docs/version-22.0/ManualMocks.md +++ b/website/versioned_docs/version-22.0/ManualMocks.md @@ -4,20 +4,9 @@ title: Manual Mocks original_id: 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 . @@ -32,15 +21,9 @@ other than the project root). Eg: └── 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 @@ -58,10 +41,7 @@ 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 -automatic mock. Our manual mock will implement custom versions of the `fs` APIs -that we can build on for our tests: +Since we'd like our tests to avoid actually hitting the disk (that's pretty slow and fragile), we create a manual mock for the `fs` module by extending an automatic mock. Our manual mock will implement custom versions of the `fs` APIs that we can build on for our tests: ```javascript // __mocks__/fs.js @@ -129,29 +109,12 @@ 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 -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. +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. -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). +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) -then you'll normally be inclined to put your `import` statements at the top of -the test file. But often you need to instruct Jest to use a mock before modules -use it. For this reason, Jest will automatically hoist `jest.mock` calls to the -top of the module (before any imports). To learn more about this and see it in -action, see [this repo](https://github.com/kentcdodds/how-jest-mocking-works). +If you're using [ES module imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) then you'll normally be inclined to put your `import` statements at the top of the test file. But often you need to instruct Jest to use a mock before modules use it. For this reason, Jest will automatically hoist `jest.mock` calls to the top of the module (before any imports). To learn more about this and see it in action, see [this repo](https://github.com/kentcdodds/how-jest-mocking-works). diff --git a/website/versioned_docs/version-22.0/MigrationGuide.md b/website/versioned_docs/version-22.0/MigrationGuide.md index 336c472e830b..6f79177a3946 100644 --- a/website/versioned_docs/version-22.0/MigrationGuide.md +++ b/website/versioned_docs/version-22.0/MigrationGuide.md @@ -4,32 +4,15 @@ title: Migrating to Jest original_id: migration-guide --- -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), -[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). +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). Install Jest Codemods with `npm` by running: @@ -37,12 +20,10 @@ 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/website/versioned_docs/version-22.0/MockFunctionAPI.md b/website/versioned_docs/version-22.0/MockFunctionAPI.md index 2ec7bb0d3856..57920f9125ac 100644 --- a/website/versioned_docs/version-22.0/MockFunctionAPI.md +++ b/website/versioned_docs/version-22.0/MockFunctionAPI.md @@ -4,10 +4,7 @@ title: Mock Functions original_id: mock-function-api --- -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 @@ -25,13 +22,9 @@ 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. +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: +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']]; @@ -39,11 +32,9 @@ a `mock.calls` array that looks like this: ### `mockFn.mock.instances` -An array that contains all the object instances that have been instantiated from -this mock function using `new`. +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: +For example: A mock function that has been instantiated twice would have the following `mock.instances` array: ```js const mockFn = jest.fn(); @@ -57,55 +48,35 @@ 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. +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. +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. +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. +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. +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. +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)`._ +_Note: `jest.fn(implementation)` is a shorthand for `jest.fn().mockImplementation(implementation)`._ For example: @@ -148,9 +119,7 @@ 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() @@ -164,10 +133,7 @@ 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') @@ -182,8 +148,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); ##### available in Jest **22.0.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: @@ -225,10 +190,7 @@ 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/website/versioned_docs/version-22.0/MockFunctions.md b/website/versioned_docs/version-22.0/MockFunctions.md index 28e1e31cde34..9078b8516a1a 100644 --- a/website/versioned_docs/version-22.0/MockFunctions.md +++ b/website/versioned_docs/version-22.0/MockFunctions.md @@ -4,20 +4,13 @@ title: Mock Functions original_id: mock-functions --- -Mock functions make it easy to test the links between code by erasing the actual -implementation of a function, capturing calls to the function (and the -parameters passed in those calls), capturing instances of constructor functions -when instantiated with `new`, and allowing test-time configuration of return -values. +Mock functions make it easy to test the links between code by erasing the actual implementation of a function, capturing calls to the function (and the parameters passed in those calls), capturing instances of constructor functions when instantiated with `new`, and allowing test-time configuration of return values. -There are two ways to mock functions: Either by creating a mock function to use -in test code, or writing a [`manual mock`](ManualMocks.md) to override a module -dependency. +There are two ways to mock functions: Either by creating a mock function to use in test code, or writing a [`manual mock`](ManualMocks.md) to override a module dependency. ## Using a mock function -Let's imagine we're testing an implementation of a function `forEach`, which -invokes a callback for each item in a supplied array. +Let's imagine we're testing an implementation of a function `forEach`, which invokes a callback for each item in a supplied array. ```javascript function forEach(items, callback) { @@ -27,8 +20,7 @@ function forEach(items, callback) { } ``` -To test this function, we can use a mock function, and inspect the mock's state -to ensure the callback is invoked as expected. +To test this function, we can use a mock function, and inspect the mock's state to ensure the callback is invoked as expected. ```javascript const mockCallback = jest.fn(); @@ -46,9 +38,7 @@ expect(mockCallback.mock.calls[1][0]).toBe(1); ## `.mock` property -All mock functions have this special `.mock` property, which is where data about -how the function has been called is kept. The `.mock` property also tracks the -value of `this` for each call, so it is possible to inspect this as well: +All mock functions have this special `.mock` property, which is where data about how the function has been called is kept. The `.mock` property also tracks the value of `this` for each call, so it is possible to inspect this as well: ```javascript const myMock = jest.fn(); @@ -62,8 +52,7 @@ console.log(myMock.mock.instances); // > [ , ] ``` -These mock members are very useful in tests to assert how these functions get -called, or instantiated: +These mock members are very useful in tests to assert how these functions get called, or instantiated: ```javascript // The function was called exactly once @@ -85,8 +74,7 @@ expect(someMockFunction.mock.instances[0].name).toEqual('test'); ## Mock Return Values -Mock functions can also be used to inject test values into your code during a -test: +Mock functions can also be used to inject test values into your code during a test: ```javascript const myMock = jest.fn(); @@ -102,11 +90,7 @@ console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true ``` -Mock functions are also very effective in code that uses a functional -continuation-passing style. Code written in this style helps avoid the need for -complicated stubs that recreate behavior of the real component they're standing -in for, in favor of injecting values directly into the test right before they're -used. +Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. ```javascript const filterTestFn = jest.fn(); @@ -123,17 +107,11 @@ console.log(filterTestFn.mock.calls); // > [ [11], [12] ] ``` -Most real-world examples actually involve getting ahold of a mock function on a -dependent component and configuring that, but the technique is the same. In -these cases, try to avoid the temptation to implement logic inside of any -function that's not directly being tested. +Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. ## Mock Implementations -Still, there are cases where it's useful to go beyond the ability to specify -return values and full-on replace the implementation of a mock function. This -can be done with `jest.fn` or the `mockImplementationOnce` method on mock -functions. +Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. ```javascript const myMockFn = jest.fn(cb => cb(null, true)); @@ -145,8 +123,7 @@ myMockFn((err, val) => console.log(val)); // > true ``` -The `mockImplementation` method is useful when you need to define the default -implementation of a mock function that is created from another module: +The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: ```js // foo.js @@ -164,9 +141,7 @@ 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: +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 @@ -181,9 +156,7 @@ myMockFn((err, val) => console.log(val)); // > false ``` -When the mocked function runs out of implementations defined with -`mockImplementationOnce`, it will execute the default implementation set with -`jest.fn` (if it is defined): +When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): ```javascript const myMockFn = jest @@ -195,9 +168,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); // > 'first call', 'second call', 'default', 'default' ``` -For cases where we have methods that are typically chained (and thus always need -to return `this`), we have a sugary API to simplify this in the form of a -`.mockReturnThis()` function that also sits on all mocks: +For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: ```javascript const myObj = { @@ -217,10 +188,7 @@ const otherObj = { ##### available in Jest **22.0.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 @@ -232,8 +200,7 @@ const myMockFn = jest ## Custom Matchers -Finally, in order to make it simpler to assert how mock functions have been -called, we've added some custom matcher functions for you: +Finally, in order to make it simpler to assert how mock functions have been called, we've added some custom matcher functions for you: ```javascript // The mock function was called at least once @@ -249,9 +216,7 @@ expect(mockFunc).lastCalledWith(arg1, arg2); expect(mockFunc).toMatchSnapshot(); ``` -These matchers are really just sugar for common forms of inspecting the `.mock` -property. You can always do this manually yourself if that's more to your taste -or if you need to do something more specific: +These matchers are really just sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: ```javascript // The mock function was called at least once diff --git a/website/versioned_docs/version-22.0/MoreResources.md b/website/versioned_docs/version-22.0/MoreResources.md index df85907a9e5e..d3468cfd060c 100644 --- a/website/versioned_docs/version-22.0/MoreResources.md +++ b/website/versioned_docs/version-22.0/MoreResources.md @@ -4,38 +4,22 @@ title: More Resources original_id: 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 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/website/versioned_docs/version-22.0/Puppeteer.md b/website/versioned_docs/version-22.0/Puppeteer.md index 89802f51bfb7..9f67a3dea881 100644 --- a/website/versioned_docs/version-22.0/Puppeteer.md +++ b/website/versioned_docs/version-22.0/Puppeteer.md @@ -4,9 +4,7 @@ title: Using with puppeteer original_id: puppeteer --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). ## A jest-puppeteer example @@ -99,5 +97,4 @@ describe( ); ``` -Here's the code of -[full working example](https://github.com/xfumihiro/jest-puppeteer-example). +Here's the code of [full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/website/versioned_docs/version-22.0/SetupAndTeardown.md b/website/versioned_docs/version-22.0/SetupAndTeardown.md index 8bb3b1c17d74..1550badd628d 100644 --- a/website/versioned_docs/version-22.0/SetupAndTeardown.md +++ b/website/versioned_docs/version-22.0/SetupAndTeardown.md @@ -4,19 +4,13 @@ title: Setup and Teardown original_id: setup-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(() => { @@ -36,11 +30,7 @@ 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(() => { @@ -50,13 +40,9 @@ 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(() => { @@ -78,13 +64,9 @@ 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 @@ -116,9 +98,7 @@ describe('matching cities to foods', () => { }); ``` -Note that the top-level `beforeEach` is executed before the `beforeEach` inside -the `describe` block. It may help to illustrate the order of execution of all -hooks. +Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. ```js beforeAll(() => console.log('1 - beforeAll')); @@ -150,12 +130,7 @@ describe('Scoped / Nested block', () => { ### Order of execution of describe and test blocks -Jest executes all describe handlers in a test file _before_ it executes any of -the actual tests. This is another reason to do setup and teardown in `before*` -and `after*` handlers rather in the describe blocks. Once the describe blocks -are complete, by default Jest runs all the tests serially in the order they were -encountered in the collection phase, waiting for each to finish and be tidied up -before moving on. +Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown in `before*` and `after*` handlers rather in the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on. Consider the following illustrative test file and output: @@ -201,9 +176,7 @@ describe('outer', () => { ### 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', () => { @@ -215,8 +188,4 @@ 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/website/versioned_docs/version-22.0/SnapshotTesting.md b/website/versioned_docs/version-22.0/SnapshotTesting.md index 9bacb3cbc825..580e40ab9a6f 100644 --- a/website/versioned_docs/version-22.0/SnapshotTesting.md +++ b/website/versioned_docs/version-22.0/SnapshotTesting.md @@ -4,23 +4,13 @@ title: Snapshot Testing original_id: 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'; @@ -35,9 +25,7 @@ it('renders correctly', () => { }); ``` -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`] = ` @@ -52,34 +40,15 @@ 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 @@ -95,127 +64,65 @@ 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/website/versioned_docs/version-22.0/TestingAsyncCode.md b/website/versioned_docs/version-22.0/TestingAsyncCode.md index 3c8288ba8e2a..87b53aac4935 100644 --- a/website/versioned_docs/version-22.0/TestingAsyncCode.md +++ b/website/versioned_docs/version-22.0/TestingAsyncCode.md @@ -4,21 +4,15 @@ title: Testing Asynchronous Code original_id: asynchronous --- -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! @@ -31,12 +25,9 @@ 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 => { @@ -49,18 +40,13 @@ 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', () => { @@ -71,12 +57,9 @@ 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', () => { @@ -89,9 +72,7 @@ test('the fetch fails with an error', () => { ##### 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', () => { @@ -100,12 +81,9 @@ 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', () => { @@ -116,9 +94,7 @@ 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 () => { @@ -137,8 +113,7 @@ 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 () => { @@ -152,9 +127,6 @@ 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/website/versioned_docs/version-22.0/TestingFrameworks.md b/website/versioned_docs/version-22.0/TestingFrameworks.md index 9766001d3fb9..01f71a702427 100644 --- a/website/versioned_docs/version-22.0/TestingFrameworks.md +++ b/website/versioned_docs/version-22.0/TestingFrameworks.md @@ -4,36 +4,26 @@ title: Testing Web Frameworks original_id: testing-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/website/versioned_docs/version-22.0/TimerMocks.md b/website/versioned_docs/version-22.0/TimerMocks.md index 297772e740a5..fd28c381d42e 100644 --- a/website/versioned_docs/version-22.0/TimerMocks.md +++ b/website/versioned_docs/version-22.0/TimerMocks.md @@ -4,11 +4,7 @@ title: Timer Mocks original_id: timer-mocks --- -The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, -`clearInterval`) are less than ideal for a testing environment since they depend -on real time to elapse. Jest can swap out timers with functions that allow you -to control the passage of time. -[Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) +The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) ```javascript // timerGame.js @@ -40,14 +36,11 @@ 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 -Another test we might want to write for this module is one that asserts that the -callback is called after 1 second. To do this, we're going to use Jest's timer -control APIs to fast-forward time right in the middle of the test: +Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test: ```javascript test('calls the callback after 1 second', () => { @@ -70,10 +63,7 @@ test('calls the callback after 1 second', () => { ## Run Pending Timers -There are also scenarios where you might have a recursive timer -- that is a -timer that sets a new timer in its own callback. For these, running all the -timers would be an endless loop… so something like `jest.runAllTimers()` is not -desirable. For these cases you might use `jest.runOnlyPendingTimers()`: +There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: ```javascript // infiniteTimerGame.js @@ -133,13 +123,7 @@ describe('infiniteTimerGame', () => { ##### renamed from `runTimersToTime` to `advanceTimersByTime` in Jest **22.0.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 @@ -175,8 +159,6 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { }); ``` -Lastly, it may occasionally be useful in some tests to be able to clear all of -the pending timers. For this, we have `jest.clearAllTimers()`. +Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at -[examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). +The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). diff --git a/website/versioned_docs/version-22.0/Troubleshooting.md b/website/versioned_docs/version-22.0/Troubleshooting.md index ac74b963ffcc..adc784e57444 100644 --- a/website/versioned_docs/version-22.0/Troubleshooting.md +++ b/website/versioned_docs/version-22.0/Troubleshooting.md @@ -10,8 +10,7 @@ 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] @@ -19,34 +18,17 @@ 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: @@ -72,8 +54,7 @@ Then attach VS Code's debugger using the following `launch.json` config: } ``` -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 { @@ -117,9 +98,7 @@ or the following for Windows: } ``` -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 { @@ -140,35 +119,21 @@ can debug your Jest tests with the following configuration: } ``` -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. +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. +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? +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 @@ -178,13 +143,9 @@ If a promise doesn't resolve at all, this error might be thrown: - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` ``` -Most commonly this is being caused by conflicting Promise implementations. -Consider replacing the global promise implementation with your own, for example -`global.Promise = require.requireActual('promise');` and/or consolidate the used -Promise libraries to a single one. +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. -If your test is long running, you may want to consider to increase the timeout -by calling `jest.setTimeout` +If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` ``` jest.setTimeout(10000); // 10 second timeout @@ -192,26 +153,17 @@ 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) -[discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/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 @@ -221,10 +173,7 @@ 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 @@ -236,22 +185,9 @@ 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. @@ -276,8 +212,7 @@ const foo = require('foo'); jest.dontMock('foo'); // Oops! ``` -In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin -for babel, this will now work properly when using `babel-jest`: +In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin for babel, this will now work properly when using `babel-jest`: ```js jest.unmock('./foo'); // Use unmock! @@ -287,30 +222,21 @@ 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? -Jest is now using Jasmine 2 by default. It should be easy to upgrade using the -Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). +Jest is now using Jasmine 2 by default. It should be easy to upgrade using the Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). -If you would like to continue using Jasmine 1, set the `testRunner` config -option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. +If you would like to continue using Jasmine 1, set the `testRunner` config option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. ### Compatibility issues -Jest takes advantage of new features added to Node 4. We recommend that you -upgrade to the latest stable release of Node. The minimum supported version is -`v4.0.0`. Versions `0.x.x` are not supported. +Jest takes advantage of new features added to Node 4. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is `v4.0.0`. Versions `0.x.x` are not supported. ### `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/website/versioned_docs/version-22.0/TutorialAsync.md b/website/versioned_docs/version-22.0/TutorialAsync.md index 19355a5cb90c..2e96e4884f40 100644 --- a/website/versioned_docs/version-22.0/TutorialAsync.md +++ b/website/versioned_docs/version-22.0/TutorialAsync.md @@ -4,11 +4,9 @@ title: An Async Example original_id: tutorial-async --- -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 @@ -19,11 +17,9 @@ export function getUserName(userID) { } ``` -In the above implementation we expect the `request.js` module to return a -promise. We chain a call to `then` to receive the user name. +In the above implementation we expect the `request.js` module to return a promise. We chain a call to `then` to receive the user name. -Now imagine an implementation of `request.js` that goes to the network and -fetches some user data: +Now imagine an implementation of `request.js` that goes to the network and fetches some user data: ```js // request.js @@ -43,9 +39,7 @@ export default function request(url) { } ``` -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 @@ -84,18 +78,13 @@ 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', () => { @@ -106,8 +95,7 @@ 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. @@ -124,15 +112,11 @@ 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. +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. ### 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. @@ -162,8 +146,7 @@ it('tests error with async/await', async () => { ##### 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`. @@ -183,8 +166,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at -[examples/async](https://github.com/facebook/jest/tree/master/examples/async). +The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/master/examples/async). -If you'd like to test timers, like `setTimeout`, take a look at the -[Timer mocks](TimerMocks.md) documentation. +If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-22.0/TutorialReact.md b/website/versioned_docs/version-22.0/TutorialReact.md index e27edbf2d010..ea6243e86eaa 100644 --- a/website/versioned_docs/version-22.0/TutorialReact.md +++ b/website/versioned_docs/version-22.0/TutorialReact.md @@ -4,26 +4,17 @@ title: Testing React Apps original_id: tutorial-react --- -At Facebook, we use Jest to test [React](http://facebook.github.io/react/) -applications. +At Facebook, we use Jest to test [React](http://facebook.github.io/react/) applications. ## Setup ### 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 @@ -31,9 +22,7 @@ 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 @@ -64,8 +53,7 @@ jest configuration entries: ### 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 @@ -111,8 +99,7 @@ export default class Link extends React.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 // Link.react.test.js @@ -176,25 +163,15 @@ 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). +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: @@ -232,9 +209,7 @@ 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 @@ -255,13 +230,11 @@ test('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at -[examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). +The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). ### 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 @@ -284,14 +257,11 @@ 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/website/versioned_docs/version-22.0/TutorialReactNative.md b/website/versioned_docs/version-22.0/TutorialReactNative.md index 256ccb74dd49..0df325074e23 100644 --- a/website/versioned_docs/version-22.0/TutorialReactNative.md +++ b/website/versioned_docs/version-22.0/TutorialReactNative.md @@ -4,20 +4,13 @@ title: Testing React Native Apps original_id: tutorial-react-native --- -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 @@ -29,16 +22,13 @@ automatically added to your package.json file: } ``` -_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 @@ -78,8 +68,7 @@ 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 @@ -134,40 +123,23 @@ 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). +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": [ @@ -177,17 +149,11 @@ react-native: ### 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": { @@ -199,25 +165,17 @@ configuration option can help: ### 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 `, ] ``` -These mock members are very useful in tests to assert how these functions get -called, or instantiated: +These mock members are very useful in tests to assert how these functions get called, or instantiated: ```javascript // The function was called exactly once @@ -85,8 +74,7 @@ expect(someMockFunction.mock.instances[0].name).toEqual('test'); ## Mock Return Values -Mock functions can also be used to inject test values into your code during a -test: +Mock functions can also be used to inject test values into your code during a test: ```javascript const myMock = jest.fn(); @@ -102,11 +90,7 @@ console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true ``` -Mock functions are also very effective in code that uses a functional -continuation-passing style. Code written in this style helps avoid the need for -complicated stubs that recreate behavior of the real component they're standing -in for, in favor of injecting values directly into the test right before they're -used. +Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. ```javascript const filterTestFn = jest.fn(); @@ -123,17 +107,11 @@ console.log(filterTestFn.mock.calls); // > [ [11], [12] ] ``` -Most real-world examples actually involve getting ahold of a mock function on a -dependent component and configuring that, but the technique is the same. In -these cases, try to avoid the temptation to implement logic inside of any -function that's not directly being tested. +Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. ## Mock Implementations -Still, there are cases where it's useful to go beyond the ability to specify -return values and full-on replace the implementation of a mock function. This -can be done with `jest.fn` or the `mockImplementationOnce` method on mock -functions. +Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. ```javascript const myMockFn = jest.fn(cb => cb(null, true)); @@ -145,8 +123,7 @@ myMockFn((err, val) => console.log(val)); // > true ``` -The `mockImplementation` method is useful when you need to define the default -implementation of a mock function that is created from another module: +The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: ```js // foo.js @@ -164,9 +141,7 @@ 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: +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 @@ -181,9 +156,7 @@ myMockFn((err, val) => console.log(val)); // > false ``` -When the mocked function runs out of implementations defined with -`mockImplementationOnce`, it will execute the default implementation set with -`jest.fn` (if it is defined): +When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): ```javascript const myMockFn = jest @@ -195,9 +168,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); // > 'first call', 'second call', 'default', 'default' ``` -For cases where we have methods that are typically chained (and thus always need -to return `this`), we have a sugary API to simplify this in the form of a -`.mockReturnThis()` function that also sits on all mocks: +For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: ```javascript const myObj = { @@ -215,10 +186,7 @@ const otherObj = { ## Mock Names -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 @@ -230,8 +198,7 @@ const myMockFn = jest ## Custom Matchers -Finally, in order to make it simpler to assert how mock functions have been -called, we've added some custom matcher functions for you: +Finally, in order to make it simpler to assert how mock functions have been called, we've added some custom matcher functions for you: ```javascript // The mock function was called at least once @@ -247,9 +214,7 @@ expect(mockFunc).lastCalledWith(arg1, arg2); expect(mockFunc).toMatchSnapshot(); ``` -These matchers are really just sugar for common forms of inspecting the `.mock` -property. You can always do this manually yourself if that's more to your taste -or if you need to do something more specific: +These matchers are really just sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: ```javascript // The mock function was called at least once diff --git a/website/versioned_docs/version-22.2/MoreResources.md b/website/versioned_docs/version-22.2/MoreResources.md index f55200b4b532..dfe7903056ef 100644 --- a/website/versioned_docs/version-22.2/MoreResources.md +++ b/website/versioned_docs/version-22.2/MoreResources.md @@ -4,38 +4,22 @@ title: More Resources original_id: 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 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/website/versioned_docs/version-22.2/Puppeteer.md b/website/versioned_docs/version-22.2/Puppeteer.md index d2481e710140..3630d37505ba 100644 --- a/website/versioned_docs/version-22.2/Puppeteer.md +++ b/website/versioned_docs/version-22.2/Puppeteer.md @@ -4,9 +4,7 @@ title: Using with puppeteer original_id: puppeteer --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). ## A jest-puppeteer example @@ -99,5 +97,4 @@ describe( ); ``` -Here's the code of -[full working example](https://github.com/xfumihiro/jest-puppeteer-example). +Here's the code of [full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/website/versioned_docs/version-22.2/SetupAndTeardown.md b/website/versioned_docs/version-22.2/SetupAndTeardown.md index 3297a759e40a..ee0bee00491c 100644 --- a/website/versioned_docs/version-22.2/SetupAndTeardown.md +++ b/website/versioned_docs/version-22.2/SetupAndTeardown.md @@ -4,19 +4,13 @@ title: Setup and Teardown original_id: setup-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(() => { @@ -36,11 +30,7 @@ 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(() => { @@ -50,13 +40,9 @@ 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(() => { @@ -78,13 +64,9 @@ 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 @@ -116,9 +98,7 @@ describe('matching cities to foods', () => { }); ``` -Note that the top-level `beforeEach` is executed before the `beforeEach` inside -the `describe` block. It may help to illustrate the order of execution of all -hooks. +Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. ```js beforeAll(() => console.log('1 - beforeAll')); @@ -150,12 +130,7 @@ describe('Scoped / Nested block', () => { ### Order of execution of describe and test blocks -Jest executes all describe handlers in a test file _before_ it executes any of -the actual tests. This is another reason to do setup and teardown in `before*` -and `after*` handlers rather in the describe blocks. Once the describe blocks -are complete, by default Jest runs all the tests serially in the order they were -encountered in the collection phase, waiting for each to finish and be tidied up -before moving on. +Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown in `before*` and `after*` handlers rather in the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on. Consider the following illustrative test file and output: @@ -201,9 +176,7 @@ describe('outer', () => { ### 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', () => { @@ -215,8 +188,4 @@ 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/website/versioned_docs/version-22.2/SnapshotTesting.md b/website/versioned_docs/version-22.2/SnapshotTesting.md index 78eb4aece0f2..b2cfdaf2ad1f 100644 --- a/website/versioned_docs/version-22.2/SnapshotTesting.md +++ b/website/versioned_docs/version-22.2/SnapshotTesting.md @@ -4,23 +4,13 @@ title: Snapshot Testing original_id: 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'; @@ -35,9 +25,7 @@ it('renders correctly', () => { }); ``` -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`] = ` @@ -52,34 +40,15 @@ 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 @@ -95,127 +64,65 @@ 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: ```bash jest --updateSnapshot ``` -Go ahead and accept the changes by running the above command. You may also use -the equivalent single-character `-u` flag to re-generate snapshots if you -prefer. This will re-generate snapshot artifacts for all failing snapshot tests. -If we had any additional failing snapshot tests due to an unintentional bug, we -would need to fix the bug before re-generating snapshots to avoid recording -snapshots of the buggy behavior. +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: ```js Date.now = jest.fn(() => 1482363367071); ``` -Now, every time the snapshot test case runs, `Date.now()` will return -`1482363367071` consistently. This will result in the same snapshot being -generated for this component regardless of when the test is run. +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](TutorialReact.md) and [React Native](TutorialReactNative.md) components -are a good use case for snapshot testing. However, snapshots can capture any -serializable value and should be used anytime the goal is testing whether the -output is correct. The Jest repository contains many examples of testing the -output of Jest itself, the output of Jest's assertion library as well as log -messages from various parts of the Jest codebase. See an example of -[snapshotting CLI output](https://github.com/facebook/jest/blob/master/integration-tests/__tests__/console.test.js) -in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/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/website/versioned_docs/version-22.2/TestingAsyncCode.md b/website/versioned_docs/version-22.2/TestingAsyncCode.md index 7293ca3aed42..7a9e84bd4c4a 100644 --- a/website/versioned_docs/version-22.2/TestingAsyncCode.md +++ b/website/versioned_docs/version-22.2/TestingAsyncCode.md @@ -4,21 +4,15 @@ title: Testing Asynchronous Code original_id: asynchronous --- -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! @@ -31,12 +25,9 @@ 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 => { @@ -49,18 +40,13 @@ 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', () => { @@ -71,12 +57,9 @@ 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', () => { @@ -87,9 +70,7 @@ test('the fetch fails with an error', () => { ### `.resolves` / `.rejects` -You can also use the `.resolves` matcher in your expect statement, and Jest will -wait for that promise to resolve. If the promise is rejected, the test will -automatically fail. +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', () => { @@ -98,12 +79,9 @@ 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', () => { @@ -114,9 +92,7 @@ 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 () => { @@ -149,9 +125,6 @@ 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/website/versioned_docs/version-22.2/TestingFrameworks.md b/website/versioned_docs/version-22.2/TestingFrameworks.md index 4da068426b60..077ba6209cf9 100644 --- a/website/versioned_docs/version-22.2/TestingFrameworks.md +++ b/website/versioned_docs/version-22.2/TestingFrameworks.md @@ -4,36 +4,26 @@ title: Testing Web Frameworks original_id: testing-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/website/versioned_docs/version-22.2/TimerMocks.md b/website/versioned_docs/version-22.2/TimerMocks.md index bd94dc57cb63..3320e20d3889 100644 --- a/website/versioned_docs/version-22.2/TimerMocks.md +++ b/website/versioned_docs/version-22.2/TimerMocks.md @@ -4,11 +4,7 @@ title: Timer Mocks original_id: timer-mocks --- -The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, -`clearInterval`) are less than ideal for a testing environment since they depend -on real time to elapse. Jest can swap out timers with functions that allow you -to control the passage of time. -[Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) +The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) ```javascript // timerGame.js @@ -40,14 +36,11 @@ 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 -Another test we might want to write for this module is one that asserts that the -callback is called after 1 second. To do this, we're going to use Jest's timer -control APIs to fast-forward time right in the middle of the test: +Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test: ```javascript test('calls the callback after 1 second', () => { @@ -70,10 +63,7 @@ test('calls the callback after 1 second', () => { ## Run Pending Timers -There are also scenarios where you might have a recursive timer -- that is a -timer that sets a new timer in its own callback. For these, running all the -timers would be an endless loop… so something like `jest.runAllTimers()` is not -desirable. For these cases you might use `jest.runOnlyPendingTimers()`: +There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: ```javascript // infiniteTimerGame.js @@ -133,13 +123,7 @@ describe('infiniteTimerGame', () => { ##### renamed from `runTimersToTime` to `advanceTimersByTime` in Jest **22.0.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 time frame, will be executed. Additionally if those -macro-tasks schedule new macro-tasks that would be executed within the same time -frame, those will be executed until there are no more macro-tasks remaining in -the queue that should be run within msToRun milliseconds. +Another possibility is use `jest.advanceTimersByTime(msToRun)`. When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue that should be run within msToRun milliseconds. ```javascript // timerGame.js @@ -175,8 +159,6 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { }); ``` -Lastly, it may occasionally be useful in some tests to be able to clear all of -the pending timers. For this, we have `jest.clearAllTimers()`. +Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at -[examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). +The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). diff --git a/website/versioned_docs/version-22.2/Troubleshooting.md b/website/versioned_docs/version-22.2/Troubleshooting.md index b9c083612cd2..29105a70d6c4 100644 --- a/website/versioned_docs/version-22.2/Troubleshooting.md +++ b/website/versioned_docs/version-22.2/Troubleshooting.md @@ -10,8 +10,7 @@ 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: ```bash node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] @@ -19,34 +18,17 @@ 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: @@ -72,8 +54,7 @@ Then attach VS Code's debugger using the following `launch.json` config: } ``` -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 { @@ -117,9 +98,7 @@ or the following for Windows: } ``` -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 { @@ -140,35 +119,21 @@ can debug your Jest tests with the following configuration: } ``` -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. +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. +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? +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 @@ -178,13 +143,9 @@ If a promise doesn't resolve at all, this error might be thrown: - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` ``` -Most commonly this is being caused by conflicting Promise implementations. -Consider replacing the global promise implementation with your own, for example -`global.Promise = require.requireActual('promise');` and/or consolidate the used -Promise libraries to a single one. +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. -If your test is long running, you may want to consider to increase the timeout -by calling `jest.setTimeout` +If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` ```js jest.setTimeout(10000); // 10 second timeout @@ -192,26 +153,17 @@ 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) -[discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/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 @@ -221,10 +173,7 @@ 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 @@ -236,22 +185,9 @@ 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. @@ -276,8 +212,7 @@ const foo = require('foo'); jest.dontMock('foo'); // Oops! ``` -In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin -for babel, this will now work properly when using `babel-jest`: +In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin for babel, this will now work properly when using `babel-jest`: ```js jest.unmock('./foo'); // Use unmock! @@ -287,30 +222,21 @@ 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? -Jest is now using Jasmine 2 by default. It should be easy to upgrade using the -Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). +Jest is now using Jasmine 2 by default. It should be easy to upgrade using the Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). -If you would like to continue using Jasmine 1, set the `testRunner` config -option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. +If you would like to continue using Jasmine 1, set the `testRunner` config option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. ### Compatibility issues -Jest takes advantage of new features added to Node 6. We recommend that you -upgrade to the latest stable release of Node. The minimum supported version is -`v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported. +Jest takes advantage of new features added to Node 6. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is `v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported. ### `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/website/versioned_docs/version-22.2/TutorialAsync.md b/website/versioned_docs/version-22.2/TutorialAsync.md index ddec114edad8..9bd79721a42c 100644 --- a/website/versioned_docs/version-22.2/TutorialAsync.md +++ b/website/versioned_docs/version-22.2/TutorialAsync.md @@ -4,11 +4,9 @@ title: An Async Example original_id: tutorial-async --- -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 @@ -19,11 +17,9 @@ export function getUserName(userID) { } ``` -In the above implementation we expect the `request.js` module to return a -promise. We chain a call to `then` to receive the user name. +In the above implementation we expect the `request.js` module to return a promise. We chain a call to `then` to receive the user name. -Now imagine an implementation of `request.js` that goes to the network and -fetches some user data: +Now imagine an implementation of `request.js` that goes to the network and fetches some user data: ```js // request.js @@ -43,9 +39,7 @@ export default function request(url) { } ``` -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 @@ -84,16 +78,11 @@ 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` -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', () => { @@ -104,8 +93,7 @@ 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. @@ -122,15 +110,11 @@ 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. +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. ### 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. @@ -158,8 +142,7 @@ it('tests error with async/await', async () => { ### `.rejects` -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`. @@ -179,8 +162,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at -[examples/async](https://github.com/facebook/jest/tree/master/examples/async). +The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/master/examples/async). -If you'd like to test timers, like `setTimeout`, take a look at the -[Timer mocks](TimerMocks.md) documentation. +If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-22.2/TutorialReact.md b/website/versioned_docs/version-22.2/TutorialReact.md index 1e3a123e3d6a..8934446e836f 100644 --- a/website/versioned_docs/version-22.2/TutorialReact.md +++ b/website/versioned_docs/version-22.2/TutorialReact.md @@ -4,26 +4,17 @@ title: Testing React Apps original_id: tutorial-react --- -At Facebook, we use Jest to test [React](http://facebook.github.io/react/) -applications. +At Facebook, we use Jest to test [React](http://facebook.github.io/react/) applications. ## Setup ### 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 @@ -31,9 +22,7 @@ Run npm install --save-dev jest babel-jest babel-preset-env babel-preset-react react-test-renderer ``` -Your `package.json` should look something like this (where `` -is the actual latest version number for the package). Please add the scripts and -jest configuration entries: +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 @@ -64,8 +53,7 @@ jest configuration entries: ### 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 @@ -111,8 +99,7 @@ export default class Link extends React.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 // Link.react.test.js @@ -176,19 +163,13 @@ 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). +The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/master/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 -There's a caveat around snapshot testing when using Enzyme and React 16+. If you -mock out a module using the following style: +There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style: ```js jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent'); @@ -203,35 +184,23 @@ Warning: is using uppercase HTML. Always use lowercase HTML ta Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. ``` -React 16 triggers these warnings due to how it checks element types, and the -mocked module fails these checks. Your options are: +React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are: -1. Render as text. This way you won't see the props passed to the mock - component in the snapshot, but it's straightforward: +1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward: ```js jest.mock('./SomeComponent', () => () => 'SomeComponent'); ``` -2. Render as a custom element. DOM "custom elements" aren't checked for - anything and shouldn't fire warnings. They are lowercase and have a dash in - the name. +2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name. ```js jest.mock('./Widget', () => 'mock-widget'); ``` -3. Use `react-test-renderer`. The test renderer doesn't care about element - types and will happily accept e.g. `SomeComponent`. You could check - snapshots using the test renderer, and check component behavior separately - using Enzyme. +3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme. ### 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: @@ -269,9 +238,7 @@ 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 @@ -292,13 +259,11 @@ test('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at -[examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). +The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). ### 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 @@ -321,14 +286,11 @@ 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/website/versioned_docs/version-22.2/TutorialReactNative.md b/website/versioned_docs/version-22.2/TutorialReactNative.md index f0c753a65fdc..fd105e41858a 100644 --- a/website/versioned_docs/version-22.2/TutorialReactNative.md +++ b/website/versioned_docs/version-22.2/TutorialReactNative.md @@ -4,20 +4,13 @@ title: Testing React Native Apps original_id: tutorial-react-native --- -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 @@ -29,16 +22,13 @@ automatically added to your package.json file: } ``` -_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 @@ -78,8 +68,7 @@ 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 @@ -134,40 +123,23 @@ 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). +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": [ @@ -177,17 +149,11 @@ react-native: ### 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": { @@ -199,26 +165,17 @@ configuration option can help: ### 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 `, ] ``` -These mock members are very useful in tests to assert how these functions get -called, or instantiated: +These mock members are very useful in tests to assert how these functions get called, or instantiated: ```javascript // The function was called exactly once @@ -85,8 +74,7 @@ expect(someMockFunction.mock.instances[0].name).toEqual('test'); ## Mock Return Values -Mock functions can also be used to inject test values into your code during a -test: +Mock functions can also be used to inject test values into your code during a test: ```javascript const myMock = jest.fn(); @@ -102,11 +90,7 @@ console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true ``` -Mock functions are also very effective in code that uses a functional -continuation-passing style. Code written in this style helps avoid the need for -complicated stubs that recreate behavior of the real component they're standing -in for, in favor of injecting values directly into the test right before they're -used. +Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. ```javascript const filterTestFn = jest.fn(); @@ -123,17 +107,11 @@ console.log(filterTestFn.mock.calls); // > [ [11], [12] ] ``` -Most real-world examples actually involve getting ahold of a mock function on a -dependent component and configuring that, but the technique is the same. In -these cases, try to avoid the temptation to implement logic inside of any -function that's not directly being tested. +Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. ## Mock Implementations -Still, there are cases where it's useful to go beyond the ability to specify -return values and full-on replace the implementation of a mock function. This -can be done with `jest.fn` or the `mockImplementationOnce` method on mock -functions. +Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. ```javascript const myMockFn = jest.fn(cb => cb(null, true)); @@ -145,8 +123,7 @@ myMockFn((err, val) => console.log(val)); // > true ``` -The `mockImplementation` method is useful when you need to define the default -implementation of a mock function that is created from another module: +The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: ```js // foo.js @@ -164,9 +141,7 @@ 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: +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 @@ -181,9 +156,7 @@ myMockFn((err, val) => console.log(val)); // > false ``` -When the mocked function runs out of implementations defined with -`mockImplementationOnce`, it will execute the default implementation set with -`jest.fn` (if it is defined): +When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): ```javascript const myMockFn = jest @@ -195,9 +168,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); // > 'first call', 'second call', 'default', 'default' ``` -For cases where we have methods that are typically chained (and thus always need -to return `this`), we have a sugary API to simplify this in the form of a -`.mockReturnThis()` function that also sits on all mocks: +For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: ```javascript const myObj = { @@ -215,10 +186,7 @@ const otherObj = { ## Mock Names -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 @@ -230,8 +198,7 @@ const myMockFn = jest ## Custom Matchers -Finally, in order to make it simpler to assert how mock functions have been -called, we've added some custom matcher functions for you: +Finally, in order to make it simpler to assert how mock functions have been called, we've added some custom matcher functions for you: ```javascript // The mock function was called at least once @@ -247,9 +214,7 @@ expect(mockFunc).lastCalledWith(arg1, arg2); expect(mockFunc).toMatchSnapshot(); ``` -These matchers are really just sugar for common forms of inspecting the `.mock` -property. You can always do this manually yourself if that's more to your taste -or if you need to do something more specific: +These matchers are really just sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: ```javascript // The mock function was called at least once diff --git a/website/versioned_docs/version-22.3/MongoDB.md b/website/versioned_docs/version-22.3/MongoDB.md index dab6900be6f7..da6bb547b8e1 100644 --- a/website/versioned_docs/version-22.3/MongoDB.md +++ b/website/versioned_docs/version-22.3/MongoDB.md @@ -4,9 +4,7 @@ title: Using with MongoDB original_id: mongodb --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [MongoDB](https://www.mongodb.com/). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). ## A jest-mongodb example @@ -124,5 +122,4 @@ it('should aggregate docs from collection', async () => { }); ``` -Here's the code of -[full working example](https://github.com/vladgolubev/jest-mongodb). +Here's the code of [full working example](https://github.com/vladgolubev/jest-mongodb). diff --git a/website/versioned_docs/version-22.3/MoreResources.md b/website/versioned_docs/version-22.3/MoreResources.md index 3a47bba502b9..57f4da467f3a 100644 --- a/website/versioned_docs/version-22.3/MoreResources.md +++ b/website/versioned_docs/version-22.3/MoreResources.md @@ -4,36 +4,22 @@ title: More Resources original_id: 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 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://discord.gg/MWRhKCj) 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://discord.gg/MWRhKCj) 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/website/versioned_docs/version-22.3/Puppeteer.md b/website/versioned_docs/version-22.3/Puppeteer.md index 076bed564f59..1ded24c1c0a3 100644 --- a/website/versioned_docs/version-22.3/Puppeteer.md +++ b/website/versioned_docs/version-22.3/Puppeteer.md @@ -4,9 +4,7 @@ title: Using with puppeteer original_id: puppeteer --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). ## A jest-puppeteer example @@ -99,5 +97,4 @@ describe( ); ``` -Here's the code of -[full working example](https://github.com/xfumihiro/jest-puppeteer-example). +Here's the code of [full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/website/versioned_docs/version-22.3/SetupAndTeardown.md b/website/versioned_docs/version-22.3/SetupAndTeardown.md index ad97a201d4dd..5a3c3a686131 100644 --- a/website/versioned_docs/version-22.3/SetupAndTeardown.md +++ b/website/versioned_docs/version-22.3/SetupAndTeardown.md @@ -4,19 +4,13 @@ title: Setup and Teardown original_id: setup-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(() => { @@ -36,11 +30,7 @@ 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(() => { @@ -50,13 +40,9 @@ 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(() => { @@ -78,13 +64,9 @@ 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 @@ -116,9 +98,7 @@ describe('matching cities to foods', () => { }); ``` -Note that the top-level `beforeEach` is executed before the `beforeEach` inside -the `describe` block. It may help to illustrate the order of execution of all -hooks. +Note that the top-level `beforeEach` is executed before the `beforeEach` inside the `describe` block. It may help to illustrate the order of execution of all hooks. ```js beforeAll(() => console.log('1 - beforeAll')); @@ -150,12 +130,7 @@ describe('Scoped / Nested block', () => { ### Order of execution of describe and test blocks -Jest executes all describe handlers in a test file _before_ it executes any of -the actual tests. This is another reason to do setup and teardown in `before*` -and `after*` handlers rather in the describe blocks. Once the describe blocks -are complete, by default Jest runs all the tests serially in the order they were -encountered in the collection phase, waiting for each to finish and be tidied up -before moving on. +Jest executes all describe handlers in a test file _before_ it executes any of the actual tests. This is another reason to do setup and teardown in `before*` and `after*` handlers rather in the describe blocks. Once the describe blocks are complete, by default Jest runs all the tests serially in the order they were encountered in the collection phase, waiting for each to finish and be tidied up before moving on. Consider the following illustrative test file and output: @@ -201,9 +176,7 @@ describe('outer', () => { ### 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', () => { @@ -215,8 +188,4 @@ 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/website/versioned_docs/version-22.3/SnapshotTesting.md b/website/versioned_docs/version-22.3/SnapshotTesting.md index fb5ffcd45e68..e311a9f49e1e 100644 --- a/website/versioned_docs/version-22.3/SnapshotTesting.md +++ b/website/versioned_docs/version-22.3/SnapshotTesting.md @@ -4,23 +4,13 @@ title: Snapshot Testing original_id: 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'; @@ -35,9 +25,7 @@ it('renders correctly', () => { }); ``` -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`] = ` @@ -52,34 +40,15 @@ 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 @@ -95,32 +64,19 @@ 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: ```bash jest --updateSnapshot ``` -Go ahead and accept the changes by running the above command. You may also use -the equivalent single-character `-u` flag to re-generate snapshots if you -prefer. This will re-generate snapshot artifacts for all failing snapshot tests. -If we had any additional failing snapshot tests due to an unintentional bug, we -would need to fix the bug before re-generating snapshots to avoid recording -snapshots of the buggy behavior. +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. ### Interactive Snapshot Mode @@ -128,9 +84,7 @@ Failed snapshots can also be updated interactively in watch mode: ![](/jest/img/content/interactiveSnapshot.png) -Once you enter Interactive Snapshot Mode, Jest will step you through the failed -snapshots one test suite at a time and give you the opportunity to review the -failed output. +Once you enter Interactive Snapshot Mode, Jest will step you through the failed snapshots one test suite at a time and give you the opportunity to review the failed output. From here you can choose to update that snapshot or skip to the next: @@ -138,64 +92,33 @@ From here you can choose to update that snapshot or skip to the next: ## Best Practices -Snapshots are a fantastic tool for identifying unexpected interface changes -within your application – whether that interface is an API response, UI, logs, -or error messages. As with any testing strategy, there are some best-practices -you should be aware of, and guidelines you should follow, in order to use them -effectively. +Snapshots are a fantastic tool for identifying unexpected interface changes within your application – whether that interface is an API response, UI, logs, or error messages. As with any testing strategy, there are some best-practices you should be aware of, and guidelines you should follow, in order to use them effectively. ### 1. Treat snapshots as code -Commit snapshots and review them as part of your regular code review process. -This means treating snapshots as you would any other type of test or code in -your project. +Commit snapshots and review them as part of your regular code review process. This means treating snapshots as you would any other type of test or code in your project. -Ensure that your snapshots are readable by keeping them focused, short, and by -using tools that enforce these stylistic conventions. +Ensure that your snapshots are readable by keeping them focused, short, and by using tools that enforce these stylistic conventions. -As mentioned previously, Jest uses -[`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make -snapshots human-readable, but you may find it useful to introduce additional -tools, like -[`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with -its -[`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-large-snapshots.md) -option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with -its component snapshot comparison feature, to promote committing short, focused -assertions. +As mentioned previously, Jest uses [`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make snapshots human-readable, but you may find it useful to introduce additional tools, like [`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with its [`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-large-snapshots.md) option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with its component snapshot comparison feature, to promote committing short, focused assertions. -The goal is to make it easy to review snapshots in pull requests, and fight -against the habit of simply regenerating snapshots when test suites fail instead -of examining the root causes of their failure. +The goal is to make it easy to review snapshots in pull requests, and fight against the habit of simply regenerating snapshots when test suites fail instead of examining the root causes of their failure. ### 2. Tests should be deterministic -Your tests should be deterministic. Running the same tests multiple times on a -component that has not changed should produce the same results every time. -You're responsible for making sure your generated snapshots do not include -platform specific or other non-deterministic data. +Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a -[Clock](https://github.com/facebook/jest/blob/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: ```js Date.now = jest.fn(() => 1482363367071); ``` -Now, every time the snapshot test case runs, `Date.now()` will return -`1482363367071` consistently. This will result in the same snapshot being -generated for this component regardless of when the test is run. +Now, every time the snapshot test case runs, `Date.now()` will return `1482363367071` consistently. This will result in the same snapshot being generated for this component regardless of when the test is run. ### 3. Use descriptive snapshot names -Always strive to use descriptive test and/or snapshot names for snapshots. The -best names describe the expected snapshot content. This makes it easier for -reviewers to verify the snapshots during review, and for anyone to know whether -or not an outdated snapshot is the correct behavior before updating. +Always strive to use descriptive test and/or snapshot names for snapshots. The best names describe the expected snapshot content. This makes it easier for reviewers to verify the snapshots during review, and for anyone to know whether or not an outdated snapshot is the correct behavior before updating. For example, compare: @@ -221,8 +144,7 @@ exports[` should render Alan Turing`] = ` `; ``` -Since the later describes exactly what's expected in the output, it's easy to -see when it's wrong: +Since the later describes exactly what's expected in the output, it's easy to see when it's wrong: ```js exports[` should render null`] = ` @@ -238,74 +160,35 @@ exports[` should render Alan Turing`] = `null`; ### Are snapshots written automatically on Continuous Integration (CI) systems? -No, as of Jest 20, snapshots in Jest are not automatically written when Jest is -run in a CI system without explicitly passing `--updateSnapshot`. It is expected -that all snapshots are part of the code that is run on CI and since new -snapshots automatically pass, they should not pass a test run on a CI system. It -is recommended to always commit all snapshots and to keep them in version -control. +No, as of Jest 20, snapshots in Jest are not automatically written when Jest is run in a CI system without explicitly passing `--updateSnapshot`. It is expected that all snapshots are part of the code that is run on CI and since new snapshots automatically pass, they should not pass a test run on a CI system. It is recommended to always commit all snapshots and to keep them in version control. ### Should snapshot files be committed? -Yes, all snapshot files should be committed alongside the modules they are -covering and their tests. They should be considered 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](TutorialReact.md) and [React Native](TutorialReactNative.md) components -are a good use case for snapshot testing. However, snapshots can capture any -serializable value and should be used anytime the goal is testing whether the -output is correct. The Jest repository contains many examples of testing the -output of Jest itself, the output of Jest's assertion library as well as log -messages from various parts of the Jest codebase. See an example of -[snapshotting CLI output](https://github.com/facebook/jest/blob/master/integration-tests/__tests__/console.test.js) -in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/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/website/versioned_docs/version-22.3/TestingAsyncCode.md b/website/versioned_docs/version-22.3/TestingAsyncCode.md index 64c421eada3f..e23d29e3f42f 100644 --- a/website/versioned_docs/version-22.3/TestingAsyncCode.md +++ b/website/versioned_docs/version-22.3/TestingAsyncCode.md @@ -4,21 +4,15 @@ title: Testing Asynchronous Code original_id: asynchronous --- -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! @@ -31,12 +25,9 @@ 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 => { @@ -49,18 +40,13 @@ 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', () => { @@ -71,12 +57,9 @@ 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', () => { @@ -87,9 +70,7 @@ test('the fetch fails with an error', () => { ### `.resolves` / `.rejects` -You can also use the `.resolves` matcher in your expect statement, and Jest will -wait for that promise to resolve. If the promise is rejected, the test will -automatically fail. +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', () => { @@ -98,12 +79,9 @@ 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', () => { @@ -114,9 +92,7 @@ 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 () => { @@ -149,9 +125,6 @@ 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/website/versioned_docs/version-22.3/TestingFrameworks.md b/website/versioned_docs/version-22.3/TestingFrameworks.md index fdf933080787..e4e86d84808a 100644 --- a/website/versioned_docs/version-22.3/TestingFrameworks.md +++ b/website/versioned_docs/version-22.3/TestingFrameworks.md @@ -4,36 +4,26 @@ title: Testing Web Frameworks original_id: testing-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/website/versioned_docs/version-22.3/TimerMocks.md b/website/versioned_docs/version-22.3/TimerMocks.md index 6aad2822ff33..9d9c38b29ccf 100644 --- a/website/versioned_docs/version-22.3/TimerMocks.md +++ b/website/versioned_docs/version-22.3/TimerMocks.md @@ -4,11 +4,7 @@ title: Timer Mocks original_id: timer-mocks --- -The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, -`clearInterval`) are less than ideal for a testing environment since they depend -on real time to elapse. Jest can swap out timers with functions that allow you -to control the passage of time. -[Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) +The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) ```javascript // timerGame.js @@ -40,14 +36,11 @@ 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 -Another test we might want to write for this module is one that asserts that the -callback is called after 1 second. To do this, we're going to use Jest's timer -control APIs to fast-forward time right in the middle of the test: +Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test: ```javascript test('calls the callback after 1 second', () => { @@ -70,10 +63,7 @@ test('calls the callback after 1 second', () => { ## Run Pending Timers -There are also scenarios where you might have a recursive timer -- that is a -timer that sets a new timer in its own callback. For these, running all the -timers would be an endless loop… so something like `jest.runAllTimers()` is not -desirable. For these cases you might use `jest.runOnlyPendingTimers()`: +There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: ```javascript // infiniteTimerGame.js @@ -133,13 +123,7 @@ describe('infiniteTimerGame', () => { ##### renamed from `runTimersToTime` to `advanceTimersByTime` in Jest **22.0.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 time frame, will be executed. Additionally if those -macro-tasks schedule new macro-tasks that would be executed within the same time -frame, those will be executed until there are no more macro-tasks remaining in -the queue that should be run within msToRun milliseconds. +Another possibility is use `jest.advanceTimersByTime(msToRun)`. When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue that should be run within msToRun milliseconds. ```javascript // timerGame.js @@ -175,8 +159,6 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { }); ``` -Lastly, it may occasionally be useful in some tests to be able to clear all of -the pending timers. For this, we have `jest.clearAllTimers()`. +Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at -[examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). +The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). diff --git a/website/versioned_docs/version-22.3/Troubleshooting.md b/website/versioned_docs/version-22.3/Troubleshooting.md index 0eb0426f1840..6529b946416c 100644 --- a/website/versioned_docs/version-22.3/Troubleshooting.md +++ b/website/versioned_docs/version-22.3/Troubleshooting.md @@ -10,8 +10,7 @@ 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: ```bash node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] @@ -19,34 +18,17 @@ 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: @@ -72,8 +54,7 @@ Then attach VS Code's debugger using the following `launch.json` config: } ``` -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 { @@ -117,9 +98,7 @@ or the following for Windows: } ``` -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 { @@ -140,35 +119,21 @@ can debug your Jest tests with the following configuration: } ``` -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. +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. +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? +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 @@ -178,13 +143,9 @@ If a promise doesn't resolve at all, this error might be thrown: - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` ``` -Most commonly this is being caused by conflicting Promise implementations. -Consider replacing the global promise implementation with your own, for example -`global.Promise = require.requireActual('promise');` and/or consolidate the used -Promise libraries to a single one. +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. -If your test is long running, you may want to consider to increase the timeout -by calling `jest.setTimeout` +If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` ```js jest.setTimeout(10000); // 10 second timeout @@ -192,26 +153,17 @@ 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) -[discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/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 @@ -221,10 +173,7 @@ 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 @@ -236,22 +185,9 @@ 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. @@ -276,8 +212,7 @@ const foo = require('foo'); jest.dontMock('foo'); // Oops! ``` -In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin -for babel, this will now work properly when using `babel-jest`: +In Jest 0.9.0, a new API `jest.unmock` was introduced. Together with a plugin for babel, this will now work properly when using `babel-jest`: ```js jest.unmock('./foo'); // Use unmock! @@ -287,30 +222,21 @@ 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? -Jest is now using Jasmine 2 by default. It should be easy to upgrade using the -Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). +Jest is now using Jasmine 2 by default. It should be easy to upgrade using the Jasmine [upgrade guide](http://jasmine.github.io/2.0/introduction.html). -If you would like to continue using Jasmine 1, set the `testRunner` config -option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. +If you would like to continue using Jasmine 1, set the `testRunner` config option to `jasmine1` or pass `--testRunner=jasmine1` as a command line option. ### Compatibility issues -Jest takes advantage of new features added to Node 6. We recommend that you -upgrade to the latest stable release of Node. The minimum supported version is -`v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported. +Jest takes advantage of new features added to Node 6. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is `v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported. ### `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/website/versioned_docs/version-22.3/TutorialAsync.md b/website/versioned_docs/version-22.3/TutorialAsync.md index 4309bb673820..e9c7f1b9d090 100644 --- a/website/versioned_docs/version-22.3/TutorialAsync.md +++ b/website/versioned_docs/version-22.3/TutorialAsync.md @@ -4,11 +4,9 @@ title: An Async Example original_id: tutorial-async --- -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 @@ -19,11 +17,9 @@ export function getUserName(userID) { } ``` -In the above implementation we expect the `request.js` module to return a -promise. We chain a call to `then` to receive the user name. +In the above implementation we expect the `request.js` module to return a promise. We chain a call to `then` to receive the user name. -Now imagine an implementation of `request.js` that goes to the network and -fetches some user data: +Now imagine an implementation of `request.js` that goes to the network and fetches some user data: ```js // request.js @@ -43,9 +39,7 @@ export default function request(url) { } ``` -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 @@ -84,16 +78,11 @@ 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` -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', () => { @@ -104,8 +93,7 @@ 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. @@ -122,15 +110,11 @@ 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. +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. ### 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. @@ -158,8 +142,7 @@ it('tests error with async/await', async () => { ### `.rejects` -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`. @@ -179,8 +162,6 @@ it('tests error with async/await and rejects', async () => { }); ``` -The code for this example is available at -[examples/async](https://github.com/facebook/jest/tree/master/examples/async). +The code for this example is available at [examples/async](https://github.com/facebook/jest/tree/master/examples/async). -If you'd like to test timers, like `setTimeout`, take a look at the -[Timer mocks](TimerMocks.md) documentation. +If you'd like to test timers, like `setTimeout`, take a look at the [Timer mocks](TimerMocks.md) documentation. diff --git a/website/versioned_docs/version-22.3/TutorialReact.md b/website/versioned_docs/version-22.3/TutorialReact.md index fb58137a3b4d..1ae63d931114 100644 --- a/website/versioned_docs/version-22.3/TutorialReact.md +++ b/website/versioned_docs/version-22.3/TutorialReact.md @@ -4,26 +4,17 @@ title: Testing React Apps original_id: tutorial-react --- -At Facebook, we use Jest to test [React](http://facebook.github.io/react/) -applications. +At Facebook, we use Jest to test [React](http://facebook.github.io/react/) applications. ## Setup ### 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 @@ -31,9 +22,7 @@ Run npm install --save-dev jest babel-jest babel-preset-env babel-preset-react react-test-renderer ``` -Your `package.json` should look something like this (where `` -is the actual latest version number for the package). Please add the scripts and -jest configuration entries: +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 @@ -64,8 +53,7 @@ jest configuration entries: ### 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 @@ -111,8 +99,7 @@ export default class Link extends React.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 // Link.react.test.js @@ -176,19 +163,13 @@ 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). +The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/master/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 -There's a caveat around snapshot testing when using Enzyme and React 16+. If you -mock out a module using the following style: +There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style: ```js jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent'); @@ -203,35 +184,23 @@ Warning: is using uppercase HTML. Always use lowercase HTML ta Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. ``` -React 16 triggers these warnings due to how it checks element types, and the -mocked module fails these checks. Your options are: +React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are: -1. Render as text. This way you won't see the props passed to the mock - component in the snapshot, but it's straightforward: +1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward: ```js jest.mock('./SomeComponent', () => () => 'SomeComponent'); ``` -2. Render as a custom element. DOM "custom elements" aren't checked for - anything and shouldn't fire warnings. They are lowercase and have a dash in - the name. +2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name. ```js jest.mock('./Widget', () => 'mock-widget'); ``` -3. Use `react-test-renderer`. The test renderer doesn't care about element - types and will happily accept e.g. `SomeComponent`. You could check - snapshots using the test renderer, and check component behavior separately - using Enzyme. +3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme. ### 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: @@ -269,9 +238,7 @@ 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 @@ -292,13 +259,11 @@ test('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at -[examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). +The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). ### 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 @@ -321,14 +286,11 @@ 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/website/versioned_docs/version-22.3/TutorialReactNative.md b/website/versioned_docs/version-22.3/TutorialReactNative.md index 5b5ae40a69e6..a3e91e3823f3 100644 --- a/website/versioned_docs/version-22.3/TutorialReactNative.md +++ b/website/versioned_docs/version-22.3/TutorialReactNative.md @@ -4,20 +4,13 @@ title: Testing React Native Apps original_id: tutorial-react-native --- -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 @@ -29,16 +22,13 @@ automatically added to your package.json file: } ``` -_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 @@ -78,8 +68,7 @@ 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 @@ -132,40 +121,23 @@ 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). +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": [ @@ -175,17 +147,11 @@ react-native: ### 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": { @@ -197,26 +163,17 @@ configuration option can help: ### 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 `, ] ``` -These mock members are very useful in tests to assert how these functions get -called, instantiated, or what they returned: +These mock members are very useful in tests to assert how these functions get called, instantiated, or what they returned: ```javascript // The function was called exactly once @@ -92,8 +80,7 @@ expect(someMockFunction.mock.instances[0].name).toEqual('test'); ## Mock Return Values -Mock functions can also be used to inject test values into your code during a -test: +Mock functions can also be used to inject test values into your code during a test: ```javascript const myMock = jest.fn(); @@ -109,11 +96,7 @@ console.log(myMock(), myMock(), myMock(), myMock()); // > 10, 'x', true, true ``` -Mock functions are also very effective in code that uses a functional -continuation-passing style. Code written in this style helps avoid the need for -complicated stubs that recreate behavior of the real component they're standing -in for, in favor of injecting values directly into the test right before they're -used. +Mock functions are also very effective in code that uses a functional continuation-passing style. Code written in this style helps avoid the need for complicated stubs that recreate behavior of the real component they're standing in for, in favor of injecting values directly into the test right before they're used. ```javascript const filterTestFn = jest.fn(); @@ -130,16 +113,11 @@ console.log(filterTestFn.mock.calls); // > [ [11], [12] ] ``` -Most real-world examples actually involve getting ahold of a mock function on a -dependent component and configuring that, but the technique is the same. In -these cases, try to avoid the temptation to implement logic inside of any -function that's not directly being tested. +Most real-world examples actually involve getting ahold of a mock function on a dependent component and configuring that, but the technique is the same. In these cases, try to avoid the temptation to implement logic inside of any function that's not directly being tested. ## Mocking Modules -Suppose we have a class that fetches users from our API. The class uses -[axios](https://github.com/axios/axios) to call the API then returns the `data` -attribute which contains all the users: +Suppose we have a class that fetches users from our API. The class uses [axios](https://github.com/axios/axios) to call the API then returns the `data` attribute which contains all the users: ```js // users.js @@ -154,13 +132,9 @@ class Users { export default Users; ``` -Now, in order to test this method without actually hitting the API (and thus -creating slow and fragile tests), we can use the `jest.mock(...)` function to -automatically mock the axios module. +Now, in order to test this method without actually hitting the API (and thus creating slow and fragile tests), we can use the `jest.mock(...)` function to automatically mock the axios module. -Once we mock the module we can provide a `mockReturnValue` for `.get` that -returns the data we want our test to assert against. In effect, we are saying -that we want axios.get('/users.json') to return a fake response. +Once we mock the module we can provide a `mockReturnValue` for `.get` that returns the data we want our test to assert against. In effect, we are saying that we want axios.get('/users.json') to return a fake response. ```js // users.test.js @@ -182,10 +156,7 @@ test('should fetch users', () => { ## Mock Implementations -Still, there are cases where it's useful to go beyond the ability to specify -return values and full-on replace the implementation of a mock function. This -can be done with `jest.fn` or the `mockImplementationOnce` method on mock -functions. +Still, there are cases where it's useful to go beyond the ability to specify return values and full-on replace the implementation of a mock function. This can be done with `jest.fn` or the `mockImplementationOnce` method on mock functions. ```javascript const myMockFn = jest.fn(cb => cb(null, true)); @@ -197,8 +168,7 @@ myMockFn((err, val) => console.log(val)); // > true ``` -The `mockImplementation` method is useful when you need to define the default -implementation of a mock function that is created from another module: +The `mockImplementation` method is useful when you need to define the default implementation of a mock function that is created from another module: ```js // foo.js @@ -216,9 +186,7 @@ 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: +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 @@ -233,9 +201,7 @@ myMockFn((err, val) => console.log(val)); // > false ``` -When the mocked function runs out of implementations defined with -`mockImplementationOnce`, it will execute the default implementation set with -`jest.fn` (if it is defined): +When the mocked function runs out of implementations defined with `mockImplementationOnce`, it will execute the default implementation set with `jest.fn` (if it is defined): ```javascript const myMockFn = jest @@ -247,9 +213,7 @@ console.log(myMockFn(), myMockFn(), myMockFn(), myMockFn()); // > 'first call', 'second call', 'default', 'default' ``` -For cases where we have methods that are typically chained (and thus always need -to return `this`), we have a sugary API to simplify this in the form of a -`.mockReturnThis()` function that also sits on all mocks: +For cases where we have methods that are typically chained (and thus always need to return `this`), we have a sugary API to simplify this in the form of a `.mockReturnThis()` function that also sits on all mocks: ```javascript const myObj = { @@ -267,10 +231,7 @@ const otherObj = { ## Mock Names -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 @@ -282,8 +243,7 @@ const myMockFn = jest ## Custom Matchers -Finally, in order to make it simpler to assert how mock functions have been -called, we've added some custom matcher functions for you: +Finally, in order to make it simpler to assert how mock functions have been called, we've added some custom matcher functions for you: ```javascript // The mock function was called at least once @@ -299,9 +259,7 @@ expect(mockFunc).lastCalledWith(arg1, arg2); expect(mockFunc).toMatchSnapshot(); ``` -These matchers are really just sugar for common forms of inspecting the `.mock` -property. You can always do this manually yourself if that's more to your taste -or if you need to do something more specific: +These matchers are really just sugar for common forms of inspecting the `.mock` property. You can always do this manually yourself if that's more to your taste or if you need to do something more specific: ```javascript // The mock function was called at least once diff --git a/website/versioned_docs/version-23.0/MongoDB.md b/website/versioned_docs/version-23.0/MongoDB.md index 654522b412ca..f042b8a438e7 100644 --- a/website/versioned_docs/version-23.0/MongoDB.md +++ b/website/versioned_docs/version-23.0/MongoDB.md @@ -4,9 +4,7 @@ title: Using with MongoDB original_id: mongodb --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [MongoDB](https://www.mongodb.com/). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [MongoDB](https://www.mongodb.com/). ## A jest-mongodb example @@ -126,5 +124,4 @@ it('should aggregate docs from collection', async () => { }); ``` -Here's the code of -[full working example](https://github.com/vladgolubev/jest-mongodb). +Here's the code of [full working example](https://github.com/vladgolubev/jest-mongodb). diff --git a/website/versioned_docs/version-23.0/MoreResources.md b/website/versioned_docs/version-23.0/MoreResources.md index ed53dd2bc5f7..efe38665d31d 100644 --- a/website/versioned_docs/version-23.0/MoreResources.md +++ b/website/versioned_docs/version-23.0/MoreResources.md @@ -4,36 +4,22 @@ title: More Resources original_id: 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 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/packages/react/src/__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/packages/react/src/__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://discord.gg/MWRhKCj) 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://discord.gg/MWRhKCj) 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/website/versioned_docs/version-23.0/Puppeteer.md b/website/versioned_docs/version-23.0/Puppeteer.md index a4d64ad633c5..1efb07f75ce2 100644 --- a/website/versioned_docs/version-23.0/Puppeteer.md +++ b/website/versioned_docs/version-23.0/Puppeteer.md @@ -4,14 +4,11 @@ title: Using with puppeteer original_id: puppeteer --- -With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and -[Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can -work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). +With the [Global Setup/Teardown](Configuration.md#globalsetup-string) and [Async Test Environment](Configuration.md#testenvironment-string) APIs, Jest can work smoothly with [puppeteer](https://github.com/GoogleChrome/puppeteer). ## Use Puppeteer Preset -[Jest Puppeteer](https://github.com/smooth-code/jest-puppeteer) provides all -required configuration to run your tests using Puppeteer. +[Jest Puppeteer](https://github.com/smooth-code/jest-puppeteer) provides all required configuration to run your tests using Puppeteer. 1. First install `jest-puppeteer` @@ -120,5 +117,4 @@ describe( ); ``` -Here's the code of -[full working example](https://github.com/xfumihiro/jest-puppeteer-example). +Here's the code of [full working example](https://github.com/xfumihiro/jest-puppeteer-example). diff --git a/website/versioned_docs/version-23.0/SnapshotTesting.md b/website/versioned_docs/version-23.0/SnapshotTesting.md index 94880cb5767a..a72fc355d13b 100644 --- a/website/versioned_docs/version-23.0/SnapshotTesting.md +++ b/website/versioned_docs/version-23.0/SnapshotTesting.md @@ -4,23 +4,13 @@ title: Snapshot Testing original_id: 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'; @@ -35,9 +25,7 @@ it('renders correctly', () => { }); ``` -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`] = ` @@ -52,34 +40,15 @@ 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 @@ -95,32 +64,19 @@ 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: ```bash jest --updateSnapshot ``` -Go ahead and accept the changes by running the above command. You may also use -the equivalent single-character `-u` flag to re-generate snapshots if you -prefer. This will re-generate snapshot artifacts for all failing snapshot tests. -If we had any additional failing snapshot tests due to an unintentional bug, we -would need to fix the bug before re-generating snapshots to avoid recording -snapshots of the buggy behavior. +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. ### Interactive Snapshot Mode @@ -128,24 +84,19 @@ Failed snapshots can also be updated interactively in watch mode: ![](/jest/img/content/interactiveSnapshot.png) -Once you enter Interactive Snapshot Mode, Jest will step you through the failed -snapshots one test at a time and give you the opportunity to review the failed -output. +Once you enter Interactive Snapshot Mode, Jest will step you through the failed snapshots one test at a time and give you the opportunity to review the failed output. From here you can choose to update that snapshot or skip to the next: ![](/jest/img/content/interactiveSnapshotUpdate.gif) -Once you're finished, Jest will give you a summary before returning back to -watch mode: +Once you're finished, Jest will give you a summary before returning back to watch mode: ![](/jest/img/content/interactiveSnapshotDone.png) ### Property Matchers -Often there are fields in the object you want to snapshot which are generated -(like IDs and Dates). If you try to snapshot these objects, they will force the -snapshot to fail on every run: +Often there are fields in the object you want to snapshot which are generated (like IDs and Dates). If you try to snapshot these objects, they will force the snapshot to fail on every run: ```javascript it('will fail every time', () => { @@ -168,9 +119,7 @@ Object { `; ``` -For these cases, Jest allows providing an asymmetric matcher for any property. -These matchers are checked before the snapshot is written or tested, and then -saved to the snapshot file instead of the received value: +For these cases, Jest allows providing an asymmetric matcher for any property. These matchers are checked before the snapshot is written or tested, and then saved to the snapshot file instead of the received value: ```javascript it('will check the matchers and pass', () => { @@ -198,64 +147,33 @@ Object { ## Best Practices -Snapshots are a fantastic tool for identifying unexpected interface changes -within your application – whether that interface is an API response, UI, logs, -or error messages. As with any testing strategy, there are some best-practices -you should be aware of, and guidelines you should follow, in order to use them -effectively. +Snapshots are a fantastic tool for identifying unexpected interface changes within your application – whether that interface is an API response, UI, logs, or error messages. As with any testing strategy, there are some best-practices you should be aware of, and guidelines you should follow, in order to use them effectively. ### 1. Treat snapshots as code -Commit snapshots and review them as part of your regular code review process. -This means treating snapshots as you would any other type of test or code in -your project. +Commit snapshots and review them as part of your regular code review process. This means treating snapshots as you would any other type of test or code in your project. -Ensure that your snapshots are readable by keeping them focused, short, and by -using tools that enforce these stylistic conventions. +Ensure that your snapshots are readable by keeping them focused, short, and by using tools that enforce these stylistic conventions. -As mentioned previously, Jest uses -[`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make -snapshots human-readable, but you may find it useful to introduce additional -tools, like -[`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with -its -[`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-large-snapshots.md) -option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with -its component snapshot comparison feature, to promote committing short, focused -assertions. +As mentioned previously, Jest uses [`pretty-format`](https://yarnpkg.com/en/package/pretty-format) to make snapshots human-readable, but you may find it useful to introduce additional tools, like [`eslint-plugin-jest`](https://yarnpkg.com/en/package/eslint-plugin-jest) with its [`no-large-snapshots`](https://github.com/jest-community/eslint-plugin-jest/blob/master/docs/rules/no-large-snapshots.md) option, or [`snapshot-diff`](https://yarnpkg.com/en/package/snapshot-diff) with its component snapshot comparison feature, to promote committing short, focused assertions. -The goal is to make it easy to review snapshots in pull requests, and fight -against the habit of simply regenerating snapshots when test suites fail instead -of examining the root causes of their failure. +The goal is to make it easy to review snapshots in pull requests, and fight against the habit of simply regenerating snapshots when test suites fail instead of examining the root causes of their failure. ### 2. Tests should be deterministic -Your tests should be deterministic. Running the same tests multiple times on a -component that has not changed should produce the same results every time. -You're responsible for making sure your generated snapshots do not include -platform specific or other non-deterministic data. +Your tests should be deterministic. Running the same tests multiple times on a component that has not changed should produce the same results every time. You're responsible for making sure your generated snapshots do not include platform specific or other non-deterministic data. -For example, if you have a -[Clock](https://github.com/facebook/jest/blob/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: ```js Date.now = jest.fn(() => 1482363367071); ``` -Now, every time the snapshot test case runs, `Date.now()` will return -`1482363367071` consistently. This will result in the same snapshot being -generated for this component regardless of when the test is run. +Now, every time the snapshot test case runs, `Date.now()` will return `1482363367071` consistently. This will result in the same snapshot being generated for this component regardless of when the test is run. ### 3. Use descriptive snapshot names -Always strive to use descriptive test and/or snapshot names for snapshots. The -best names describe the expected snapshot content. This makes it easier for -reviewers to verify the snapshots during review, and for anyone to know whether -or not an outdated snapshot is the correct behavior before updating. +Always strive to use descriptive test and/or snapshot names for snapshots. The best names describe the expected snapshot content. This makes it easier for reviewers to verify the snapshots during review, and for anyone to know whether or not an outdated snapshot is the correct behavior before updating. For example, compare: @@ -281,8 +199,7 @@ exports[` should render Alan Turing`] = ` `; ``` -Since the later describes exactly what's expected in the output, it's easy to -see when it's wrong: +Since the later describes exactly what's expected in the output, it's easy to see when it's wrong: ```js exports[` should render null`] = ` @@ -298,74 +215,35 @@ exports[` should render Alan Turing`] = `null`; ### Are snapshots written automatically on Continuous Integration (CI) systems? -No, as of Jest 20, snapshots in Jest are not automatically written when Jest is -run in a CI system without explicitly passing `--updateSnapshot`. It is expected -that all snapshots are part of the code that is run on CI and since new -snapshots automatically pass, they should not pass a test run on a CI system. It -is recommended to always commit all snapshots and to keep them in version -control. +No, as of Jest 20, snapshots in Jest are not automatically written when Jest is run in a CI system without explicitly passing `--updateSnapshot`. It is expected that all snapshots are part of the code that is run on CI and since new snapshots automatically pass, they should not pass a test run on a CI system. It is recommended to always commit all snapshots and to keep them in version control. ### Should snapshot files be committed? -Yes, all snapshot files should be committed alongside the modules they are -covering and their tests. They should be considered 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](TutorialReact.md) and [React Native](TutorialReactNative.md) components -are a good use case for snapshot testing. However, snapshots can capture any -serializable value and should be used anytime the goal is testing whether the -output is correct. The Jest repository contains many examples of testing the -output of Jest itself, the output of Jest's assertion library as well as log -messages from various parts of the Jest codebase. See an example of -[snapshotting CLI output](https://github.com/facebook/jest/blob/master/integration-tests/__tests__/console.test.js) -in the Jest repo. +[React](TutorialReact.md) and [React Native](TutorialReactNative.md) components are a good use case for snapshot testing. However, snapshots can capture any serializable value and should be used anytime the goal is testing whether the output is correct. The Jest repository contains many examples of testing the output of Jest itself, the output of Jest's assertion library as well as log messages from various parts of the Jest codebase. See an example of [snapshotting CLI output](https://github.com/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/website/versioned_docs/version-23.0/TestingFrameworks.md b/website/versioned_docs/version-23.0/TestingFrameworks.md index 2d62b928d0b2..1e067e07a814 100644 --- a/website/versioned_docs/version-23.0/TestingFrameworks.md +++ b/website/versioned_docs/version-23.0/TestingFrameworks.md @@ -4,34 +4,25 @@ title: Testing Web Frameworks original_id: testing-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 diff --git a/website/versioned_docs/version-23.0/TimerMocks.md b/website/versioned_docs/version-23.0/TimerMocks.md index 5bab2077519c..052eb097b2fd 100644 --- a/website/versioned_docs/version-23.0/TimerMocks.md +++ b/website/versioned_docs/version-23.0/TimerMocks.md @@ -4,11 +4,7 @@ title: Timer Mocks original_id: timer-mocks --- -The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, -`clearInterval`) are less than ideal for a testing environment since they depend -on real time to elapse. Jest can swap out timers with functions that allow you -to control the passage of time. -[Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) +The native timer functions (i.e., `setTimeout`, `setInterval`, `clearTimeout`, `clearInterval`) are less than ideal for a testing environment since they depend on real time to elapse. Jest can swap out timers with functions that allow you to control the passage of time. [Great Scott!](https://www.youtube.com/watch?v=5gVv10J4nio) ```javascript // timerGame.js @@ -40,17 +36,11 @@ 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. If running multiple -tests inside of one file or describe block, `jest.useFakeTimers();` can be -called before each test manually or with a setup function such as `beforeEach`. -Not doing so will result in the internal usage counter not being reset. +Here we enable fake timers by calling `jest.useFakeTimers();`. This mocks out setTimeout and other timer functions with mock functions. If running multiple tests inside of one file or describe block, `jest.useFakeTimers();` can be called before each test manually or with a setup function such as `beforeEach`. Not doing so will result in the internal usage counter not being reset. ## Run All Timers -Another test we might want to write for this module is one that asserts that the -callback is called after 1 second. To do this, we're going to use Jest's timer -control APIs to fast-forward time right in the middle of the test: +Another test we might want to write for this module is one that asserts that the callback is called after 1 second. To do this, we're going to use Jest's timer control APIs to fast-forward time right in the middle of the test: ```javascript test('calls the callback after 1 second', () => { @@ -73,10 +63,7 @@ test('calls the callback after 1 second', () => { ## Run Pending Timers -There are also scenarios where you might have a recursive timer -- that is a -timer that sets a new timer in its own callback. For these, running all the -timers would be an endless loop… so something like `jest.runAllTimers()` is not -desirable. For these cases you might use `jest.runOnlyPendingTimers()`: +There are also scenarios where you might have a recursive timer -- that is a timer that sets a new timer in its own callback. For these, running all the timers would be an endless loop… so something like `jest.runAllTimers()` is not desirable. For these cases you might use `jest.runOnlyPendingTimers()`: ```javascript // infiniteTimerGame.js @@ -136,13 +123,7 @@ describe('infiniteTimerGame', () => { ##### renamed from `runTimersToTime` to `advanceTimersByTime` in Jest **22.0.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 time frame, will be executed. Additionally if those -macro-tasks schedule new macro-tasks that would be executed within the same time -frame, those will be executed until there are no more macro-tasks remaining in -the queue that should be run within msToRun milliseconds. +Another possibility is use `jest.advanceTimersByTime(msToRun)`. When this API is called, all timers are advanced by `msToRun` milliseconds. All pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed during this time frame, will be executed. Additionally if those macro-tasks schedule new macro-tasks that would be executed within the same time frame, those will be executed until there are no more macro-tasks remaining in the queue that should be run within msToRun milliseconds. ```javascript // timerGame.js @@ -178,8 +159,6 @@ it('calls the callback after 1 second via advanceTimersByTime', () => { }); ``` -Lastly, it may occasionally be useful in some tests to be able to clear all of -the pending timers. For this, we have `jest.clearAllTimers()`. +Lastly, it may occasionally be useful in some tests to be able to clear all of the pending timers. For this, we have `jest.clearAllTimers()`. -The code for this example is available at -[examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). +The code for this example is available at [examples/timer](https://github.com/facebook/jest/tree/master/examples/timer). diff --git a/website/versioned_docs/version-23.0/Troubleshooting.md b/website/versioned_docs/version-23.0/Troubleshooting.md index 672b6a10406c..401b4c890e9a 100644 --- a/website/versioned_docs/version-23.0/Troubleshooting.md +++ b/website/versioned_docs/version-23.0/Troubleshooting.md @@ -8,11 +8,9 @@ Uh oh, something went wrong? Use this guide to resolve issues with Jest. ### Tests are Failing and You Don't Know Why -Try using the debugging support built into Node. Note: This will only work in -Node.js 8+. +Try using the debugging support built into Node. Note: This will only work in Node.js 8+. -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: ```bash node --inspect-brk node_modules/.bin/jest --runInBand [any other arguments here] @@ -20,34 +18,17 @@ 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: @@ -73,8 +54,7 @@ Then attach VS Code's debugger using the following `launch.json` config: } ``` -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 { @@ -118,9 +98,7 @@ or the following for Windows: } ``` -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 { @@ -141,35 +119,21 @@ can debug your Jest tests with the following configuration: } ``` -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. +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. +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? +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 @@ -179,13 +143,9 @@ If a promise doesn't resolve at all, this error might be thrown: - Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.` ``` -Most commonly this is being caused by conflicting Promise implementations. -Consider replacing the global promise implementation with your own, for example -`global.Promise = require.requireActual('promise');` and/or consolidate the used -Promise libraries to a single one. +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. -If your test is long running, you may want to consider to increase the timeout -by calling `jest.setTimeout` +If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout` ```js jest.setTimeout(10000); // 10 second timeout @@ -193,26 +153,17 @@ 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) -[discovered](https://github.com/facebook/jest/issues/1524#issuecomment-260246008). +While Jest is most of the time extremely fast on modern multi-core computers with fast SSDs, it may be slow on certain setups as our users [have](https://github.com/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 @@ -222,10 +173,7 @@ jest --runInBand yarn test --runInBand ``` -Another alternative to expediting test execution time on Continuous Integration -Servers such as Travis-CI is to set the max worker pool to ~_4_. Specifically on -Travis-CI, this can reduce test execution time in half. Note: The Travis CI -_free_ plan available for open source projects only includes 2 CPU cores. +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 @@ -237,22 +185,11 @@ yarn test --maxWorkers=4 ### Compatibility issues -Jest takes advantage of new features added to Node 6. We recommend that you -upgrade to the latest stable release of Node. The minimum supported version is -`v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported because the `jsdom` -version used in Jest doesn't support Node 4. However, if you need to run Jest on -Node 4, you can use the `testEnvironment` config to use a -[custom environment](https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string) -that supports Node 4, such as -[`jest-environment-node`](https://yarnpkg.com/en/package/jest-environment-node). +Jest takes advantage of new features added to Node 6. We recommend that you upgrade to the latest stable release of Node. The minimum supported version is `v6.0.0`. Versions `0.x.x` and `4.x.x` are not supported because the `jsdom` version used in Jest doesn't support Node 4. However, if you need to run Jest on Node 4, you can use the `testEnvironment` config to use a [custom environment](https://facebook.github.io/jest/docs/en/configuration.html#testenvironment-string) that supports Node 4, such as [`jest-environment-node`](https://yarnpkg.com/en/package/jest-environment-node). ### `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/website/versioned_docs/version-23.0/TutorialReact.md b/website/versioned_docs/version-23.0/TutorialReact.md index 5e57ac3dbf5d..c22079bde7ba 100644 --- a/website/versioned_docs/version-23.0/TutorialReact.md +++ b/website/versioned_docs/version-23.0/TutorialReact.md @@ -4,18 +4,13 @@ title: Testing React Apps original_id: tutorial-react --- -At Facebook, we use Jest to test [React](http://facebook.github.io/react/) -applications. +At Facebook, we use Jest to test [React](http://facebook.github.io/react/) applications. ## Setup ### 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 will only need to add `react-test-renderer` for rendering snapshots. +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 will only need to add `react-test-renderer` for rendering snapshots. Run @@ -25,10 +20,7 @@ yarn add --dev react-test-renderer ### Setup without Create React App -If you have an existing application you'll need to install a few packages to -make everything work well together. We are using the `babel-jest` package and -the `react` babel preset to transform our code inside of the test environment. -Also see [using babel](GettingStarted.md#using-babel). +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 @@ -36,9 +28,7 @@ Run yarn add --dev jest babel-jest babel-preset-env babel-preset-react react-test-renderer ``` -Your `package.json` should look something like this (where `` -is the actual latest version number for the package). Please add the scripts and -jest configuration entries: +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 @@ -69,8 +59,7 @@ jest configuration entries: ### 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 @@ -116,8 +105,7 @@ export default class Link extends React.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 // Link.react.test.js @@ -181,19 +169,13 @@ 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). +The code for this example is available at [examples/snapshot](https://github.com/facebook/jest/tree/master/examples/snapshot). #### Snapshot Testing with Mocks, Enzyme and React 16 -There's a caveat around snapshot testing when using Enzyme and React 16+. If you -mock out a module using the following style: +There's a caveat around snapshot testing when using Enzyme and React 16+. If you mock out a module using the following style: ```js jest.mock('../SomeDirectory/SomeComponent', () => 'SomeComponent'); @@ -208,34 +190,23 @@ Warning: is using uppercase HTML. Always use lowercase HTML ta Warning: The tag is unrecognized in this browser. If you meant to render a React component, start its name with an uppercase letter. ``` -React 16 triggers these warnings due to how it checks element types, and the -mocked module fails these checks. Your options are: +React 16 triggers these warnings due to how it checks element types, and the mocked module fails these checks. Your options are: -1. Render as text. This way you won't see the props passed to the mock - component in the snapshot, but it's straightforward: +1. Render as text. This way you won't see the props passed to the mock component in the snapshot, but it's straightforward: ```js jest.mock('./SomeComponent', () => () => 'SomeComponent'); ``` -2. Render as a custom element. DOM "custom elements" aren't checked for - anything and shouldn't fire warnings. They are lowercase and have a dash in - the name. +2. Render as a custom element. DOM "custom elements" aren't checked for anything and shouldn't fire warnings. They are lowercase and have a dash in the name. ```js jest.mock('./Widget', () => 'mock-widget'); ``` -3. Use `react-test-renderer`. The test renderer doesn't care about element - types and will happily accept e.g. `SomeComponent`. You could check - snapshots using the test renderer, and check component behavior separately - using Enzyme. +3. Use `react-test-renderer`. The test renderer doesn't care about element types and will happily accept e.g. `SomeComponent`. You could check snapshots using the test renderer, and check component behavior separately using Enzyme. ### 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 `yarn add --dev enzyme` to use Enzyme. If you are using a React -version below 15.5.0, you will also need to install `react-addons-test-utils`. +You have to run `yarn add --dev enzyme` to use Enzyme. If you are using a React version below 15.5.0, you will also need to install `react-addons-test-utils`. Let's implement a simple checkbox which swaps between two labels: @@ -273,9 +244,7 @@ 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 @@ -296,13 +265,11 @@ test('CheckboxWithLabel changes the text after click', () => { }); ``` -The code for this example is available at -[examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). +The code for this example is available at [examples/enzyme](https://github.com/facebook/jest/tree/master/examples/enzyme). ### 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 @@ -324,14 +291,11 @@ 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/website/versioned_docs/version-23.0/WatchPlugins.md b/website/versioned_docs/version-23.0/WatchPlugins.md index 6578f57c60b3..7d1fb0224f3c 100644 --- a/website/versioned_docs/version-23.0/WatchPlugins.md +++ b/website/versioned_docs/version-23.0/WatchPlugins.md @@ -4,10 +4,7 @@ title: Watch Plugins original_id: watch-plugins --- -The Jest watch plugin system provides a way to hook into specific parts of Jest -and to define watch mode menu prompts that execute code on key press. Combined, -these features allow you to develop interactive experiences custom for your -workflow. +The Jest watch plugin system provides a way to hook into specific parts of Jest and to define watch mode menu prompts that execute code on key press. Combined, these features allow you to develop interactive experiences custom for your workflow. ## Watch Plugin Interface @@ -26,14 +23,11 @@ class MyWatchPlugin { ## Hooking into Jest -Custom watch plugins can add hooks to Jest events. These hooks can be added -either with or without having an interactive key in the watch mode menu. +Custom watch plugins can add hooks to Jest events. These hooks can be added either with or without having an interactive key in the watch mode menu. ### `apply(jestHooks)` -Jest hooks can be attached by implementing the `apply` method. This method -receives a `jestHooks` argument that allows the plugin to hook into specific -parts of the lifecycle of a test run. +Jest hooks can be attached by implementing the `apply` method. This method receives a `jestHooks` argument that allows the plugin to hook into specific parts of the lifecycle of a test run. ```javascript class MyWatchPlugin { @@ -45,8 +39,7 @@ Below are the hooks available in Jest. #### `jestHooks.shouldRunTestSuite(testPath)` -Returns a boolean (or `Promise`) for handling asynchronous operations) -to specify if a test should be run or not. +Returns a boolean (or `Promise`) for handling asynchronous operations) to specify if a test should be run or not. For example: @@ -67,8 +60,7 @@ class MyWatchPlugin { #### `jestHooks.onTestRunComplete(results)` -Gets called at the end of every test run. It has the test results as an -argument. +Gets called at the end of every test run. It has the test results as an argument. For example: @@ -86,8 +78,7 @@ class MyWatchPlugin { Gets called whenever there is a change in the file system -* `projects: Array`: Includes - all the test paths that Jest is watching. +* `projects: Array`: Includes all the test paths that Jest is watching. For example: @@ -103,14 +94,11 @@ class MyWatchPlugin { ## Watch Menu Integration -Custom watch plugins can also add or override functionality to the watch menu by -specifying a key/prompt pair in `getUsageInfo` method and a `run` method for the -execution of the key. +Custom watch plugins can also add or override functionality to the watch menu by specifying a key/prompt pair in `getUsageInfo` method and a `run` method for the execution of the key. ### `getUsageInfo(globalConfig)` -To add a key to the watch menu, implement the `getUsageInfo` method, returning a -key and the prompt: +To add a key to the watch menu, implement the `getUsageInfo` method, returning a key and the prompt: ```javascript class MyWatchPlugin { @@ -134,19 +122,14 @@ Watch Usage › Press Enter to trigger a test run. ``` -**Note**: If the key for your plugin already exists as a default key, your -plugin will override that key. +**Note**: If the key for your plugin already exists as a default key, your plugin will override that key. ### `run(globalConfig, updateConfigAndRun)` -To handle key press events from the key returned by `getUsageInfo`, you can -implement the `run` method. This method returns a `Promise` that can be -resolved when the plugin wants to return control to Jest. The `boolean` -specifies if Jest should rerun the tests after it gets the control back. +To handle key press events from the key returned by `getUsageInfo`, you can implement the `run` method. This method returns a `Promise` that can be resolved when the plugin wants to return control to Jest. The `boolean` specifies if Jest should rerun the tests after it gets the control back. * `globalConfig`: A representation of Jest's current global configuration -* `updateConfigAndRun`: Allows you to trigger a test run while the interactive - plugin is running. +* `updateConfigAndRun`: Allows you to trigger a test run while the interactive plugin is running. ```javascript class MyWatchPlugin { diff --git a/website/versioned_docs/version-23.0/Webpack.md b/website/versioned_docs/version-23.0/Webpack.md index 848acde7a66d..8bf03dce9486 100644 --- a/website/versioned_docs/version-23.0/Webpack.md +++ b/website/versioned_docs/version-23.0/Webpack.md @@ -4,16 +4,11 @@ title: Using with webpack original_id: webpack --- -Jest can be used in projects that use [webpack](https://webpack.js.org/) to -manage assets, styles, and compilation. webpack _does_ offer some unique -challenges over other tools because it integrates directly with your application -to allow managing stylesheets, assets like images and fonts, along with the -expansive ecosystem of compile-to-JavaScript languages and tools. +Jest can be used in projects that use [webpack](https://webpack.js.org/) to manage assets, styles, and compilation. webpack _does_ offer some unique challenges over other tools because it integrates directly with your application to allow managing stylesheets, assets like images and fonts, along with the expansive ecosystem of compile-to-JavaScript languages and tools. ## A webpack example -Let's start with a common sort of webpack config file and translate it to a Jest -setup. +Let's start with a common sort of webpack config file and translate it to a Jest setup. ```js // webpack.config.js @@ -42,18 +37,11 @@ module.exports = { }; ``` -If you have JavaScript files that are transformed by Babel, you can -[enable support for Babel](GettingStarted.md#using-babel) by installing the -`babel-jest` plugin. Non-Babel JavaScript transformations can be handled with -Jest's [`transform`](Configuration.md#transform-object-string-string) config -option. +If you have JavaScript files that are transformed by Babel, you can [enable support for Babel](GettingStarted.md#using-babel) by installing the `babel-jest` plugin. Non-Babel JavaScript transformations can be handled with Jest's [`transform`](Configuration.md#transform-object-string-string) config option. ### Handling Static Assets -Next, let's configure Jest to gracefully handle asset files such as stylesheets -and images. Usually, these files aren't particularly useful in tests so we can -safely mock them out. However, if you are using CSS Modules then it's better to -mock a proxy for your className lookups. +Next, let's configure Jest to gracefully handle asset files such as stylesheets and images. Usually, these files aren't particularly useful in tests so we can safely mock them out. However, if you are using CSS Modules then it's better to mock a proxy for your className lookups. ```json // package.json @@ -84,16 +72,13 @@ module.exports = 'test-file-stub'; ### Mocking CSS Modules -You can use an [ES6 Proxy](https://github.com/keyanzhang/identity-obj-proxy) to -mock [CSS Modules](https://github.com/css-modules/css-modules): +You can use an [ES6 Proxy](https://github.com/keyanzhang/identity-obj-proxy) to mock [CSS Modules](https://github.com/css-modules/css-modules): ```bash yarn add --dev identity-obj-proxy ``` -Then all your className lookups on the styles object will be returned as-is -(e.g., `styles.foobar === 'foobar'`). This is pretty handy for React -[Snapshot Testing](SnapshotTesting.md). +Then all your className lookups on the styles object will be returned as-is (e.g., `styles.foobar === 'foobar'`). This is pretty handy for React [Snapshot Testing](SnapshotTesting.md). ```json // package.json (for CSS Modules) @@ -108,15 +93,9 @@ Then all your className lookups on the styles object will be returned as-is } ``` -> Notice that Proxy is enabled in Node 6 by default. If you are not on Node 6 -> yet, make sure you invoke Jest using -> `node --harmony_proxies node_modules/.bin/jest`. +> Notice that Proxy is enabled in Node 6 by default. If you are not on Node 6 yet, make sure you invoke Jest using `node --harmony_proxies node_modules/.bin/jest`. -If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's -[`transform`](Configuration.md#transform-object-string-string) config option to -specify how assets are transformed. For example, a transformer that returns the -basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be -written as: +If `moduleNameMapper` cannot fulfill your requirements, you can use Jest's [`transform`](Configuration.md#transform-object-string-string) config option to specify how assets are transformed. For example, a transformer that returns the basename of a file (such that `require('logo.jpg');` returns `'logo'`) can be written as: ```js // fileTransformer.js @@ -144,13 +123,9 @@ module.exports = { } ``` -We've told Jest to ignore files matching a stylesheet or image extension, and -instead, require our mock files. You can adjust the regular expression to match -the file types your webpack config handles. +We've told Jest to ignore files matching a stylesheet or image extension, and instead, require our mock files. You can adjust the regular expression to match the file types your webpack config handles. -_Note: if you are using babel-jest with additional code preprocessors, you have -to explicitly define babel-jest as a transformer for your JavaScript code to map -`.js` files to the babel-jest module._ +_Note: if you are using babel-jest with additional code preprocessors, you have to explicitly define babel-jest as a transformer for your JavaScript code to map `.js` files to the babel-jest module._ ```json "transform": { @@ -162,9 +137,7 @@ to explicitly define babel-jest as a transformer for your JavaScript code to map ### Configuring Jest to find our files -Now that Jest knows how to process our files, we need to tell it how to _find_ -them. For webpack's `modulesDirectories`, and `extensions` options there are -direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. +Now that Jest knows how to process our files, we need to tell it how to _find_ them. For webpack's `modulesDirectories`, and `extensions` options there are direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. ```json // package.json @@ -181,13 +154,9 @@ direct analogs in Jest's `moduleDirectories` and `moduleFileExtensions` options. } ``` -> Note: `` is a special token that gets replaced by Jest with the root -> of your project. Most of the time this will be the folder where your -> `package.json` is located unless you specify a custom `rootDir` option in your -> configuration. +> Note: `` is a special token that gets replaced by Jest with the root of your project. Most of the time this will be the folder where your `package.json` is located unless you specify a custom `rootDir` option in your configuration. -Similarly webpack's `resolve.root` option functions like setting the `NODE_PATH` -env variable, which you can set, or make use of the `modulePaths` option. +Similarly webpack's `resolve.root` option functions like setting the `NODE_PATH` env variable, which you can set, or make use of the `modulePaths` option. ```json // package.json @@ -204,8 +173,7 @@ env variable, which you can set, or make use of the `modulePaths` option. } ``` -And finally we just have the webpack `alias` left to handle. For that we can -make use of the `moduleNameMapper` option again. +And finally we just have the webpack `alias` left to handle. For that we can make use of the `moduleNameMapper` option again. ```json // package.json @@ -226,21 +194,13 @@ make use of the `moduleNameMapper` option again. } ``` -That's it! webpack is a complex and flexible tool, so you may have to make some -adjustments to handle your specific application's needs. Luckily for most -projects, Jest should be more than flexible enough to handle your webpack -config. +That's it! webpack is a complex and flexible tool, so you may have to make some adjustments to handle your specific application's needs. Luckily for most projects, Jest should be more than flexible enough to handle your webpack config. -> Note: For more complex webpack configurations, you may also want to -> investigate projects such as: -> [babel-plugin-webpack-loaders](https://github.com/istarkov/babel-plugin-webpack-loaders). +> Note: For more complex webpack configurations, you may also want to investigate projects such as: [babel-plugin-webpack-loaders](https://github.com/istarkov/babel-plugin-webpack-loaders). ## Using with webpack 2 -webpack 2 offers native support for ES modules. However, Jest runs in Node, and -thus requires ES modules to be transpiled to CommonJS modules. As such, if you -are using webpack 2, you most likely will want to configure Babel to transpile -ES modules to CommonJS modules only in the `test` environment. +webpack 2 offers native support for ES modules. However, Jest runs in Node, and thus requires ES modules to be transpiled to CommonJS modules. As such, if you are using webpack 2, you most likely will want to configure Babel to transpile ES modules to CommonJS modules only in the `test` environment. ```json // .babelrc @@ -255,11 +215,9 @@ ES modules to CommonJS modules only in the `test` environment. } ``` -> Note: Jest caches files to speed up test execution. If you updated .babelrc -> and Jest is still not working, try running Jest with `--no-cache`. +> Note: Jest caches files to speed up test execution. If you updated .babelrc and Jest is still not working, try running Jest with `--no-cache`. -If you use dynamic imports (`import('some-file.js').then(module => ...)`), you -need to enable the `dynamic-import-node` plugin. +If you use dynamic imports (`import('some-file.js').then(module => ...)`), you need to enable the `dynamic-import-node` plugin. ```json // .babelrc @@ -276,6 +234,4 @@ need to enable the `dynamic-import-node` plugin. } ``` -For an example of how to use Jest with Webpack with React, Redux, and Node, you -can view one -[here](https://github.com/jenniferkaplannyc/jest_react_redux_node_webpack_complex_example). +For an example of how to use Jest with Webpack with React, Redux, and Node, you can view one [here](https://github.com/jenniferkaplannyc/jest_react_redux_node_webpack_complex_example).