Skip to content

Commit

Permalink
Simplify the website + Jest 16 blog post.
Browse files Browse the repository at this point in the history
  • Loading branch information
cpojer committed Oct 3, 2016
1 parent 063828b commit 94238b0
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 313 deletions.
149 changes: 19 additions & 130 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,10 @@ Painless JavaScript Testing
## Getting Started

<generated_getting_started_start />
[Egghead.io video](https://egghead.io/lessons/javascript-test-javascript-with-jest)

Install Jest with `npm` by running:

```
npm install --save-dev jest
```

Great! Now let's get started by writing a test for a hypothetical `sum.js` file:
Install Jest with `npm` by running `npm install --save-dev jest`. Let's get started by writing a test for a hypothetical `sum.js` file:

```javascript
function sum(a, b) {
return a + b;
}
module.exports = sum;
module.exports = (a, b) => a + b;
```

Create a directory `__tests__/` with a file `sum-test.js` or name it `sum.test.js` or `sum.spec.js` and put it anywhere in your project:
Expand All @@ -46,29 +35,20 @@ Add the following to your `package.json`:
}
```

Run `npm test`:

```
PASS __tests__/sum-test.js
```

Please read the [API documentation](https://facebook.github.io/jest/docs/api.html) to learn about all available assertions, ways of writing tests, configuration options and Jest specific APIs. There is also a great introductory guide available at [Plotly Academy](https://academy.plot.ly/react/6-testing) that walks you through testing a react and redux application.

The code for this example is available at [examples/getting_started](https://github.com/facebook/jest/tree/master/examples/getting_started).
Run `npm test` and Jest will print this message: `PASS __tests__/sum-test.js`. You just successfully wrote your first test using Jest!

The [React](https://github.com/facebook/react/tree/master/src/renderers/shared/stack/reconciler/__tests__), [Relay](https://github.com/facebook/relay/tree/master/src/container/__tests__) and [react-native](https://github.com/facebook/react-native/tree/master/Libraries/Animated/src/__tests__) repositories have excellent examples of tests written by Facebook engineers.
**You are ready to use Jest! Here are some more resources to help you get started:**

**And you are ready to use Jest!**
* Read the [API Documentation](https://facebook.github.io/jest/docs/api.html) to learn about all available assertions, ways of writing tests and Jest specific APIs.
* [Jest Configuration](https://facebook.github.io/jest/docs/configuration.html).
* [Example Code](https://github.com/facebook/jest/tree/master/examples/getting_started).
* [Migration from other test runners](https://facebook.github.io/jest/docs/migration-guide.html).
* Introductory guide at [Plotly Academy](https://academy.plot.ly/react/6-testing) that walks you through testing a React and Redux application.
* The [React](https://github.com/facebook/react/tree/master/src/renderers/shared/stack/reconciler/__tests__), [Relay](https://github.com/facebook/relay/tree/master/src/container/__tests__) and [react-native](https://github.com/facebook/react-native/tree/master/Libraries/Animated/src/__tests__) repositories have excellent examples of tests written by Facebook engineers.

### Babel Integration

[Egghead.io video](https://egghead.io/lessons/javascript-add-babel-integration-with-jest)

If you'd like to use [Babel](http://babeljs.io/), it can easily be enabled:

```
npm install --save-dev babel-jest babel-polyfill
```
If you'd like to use [Babel](http://babeljs.io/), it can easily be enabled: `npm install --save-dev babel-jest babel-polyfill`.

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 ES2015 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:

Expand All @@ -80,19 +60,17 @@ Don't forget to add a [`.babelrc`](https://babeljs.io/docs/usage/babelrc/) file

You are now set up to use all ES2015 features and React specific syntax.

If you are using a more complicated Babel configuration, using Babel's `env` option,
*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.

### React, React-Native and Snapshot Testing
It will not use `development` section like Babel does by default when no `NODE_ENV` is set.*

Check out the [React tutorial](https://facebook.github.io/jest/docs/tutorial-react.html) and the [React-Native tutorial](https://facebook.github.io/jest/docs/tutorial-react-native.html) to get started with React or React-Native codebases.
### React, React Native and Snapshot Testing

We recommend using React's test renderer (`npm install --save-dev react-test-renderer`) to capture snapshots with Jest's snapshot feature. Write a test using `toMatchSnapshot`:
Check out the [React tutorial](https://facebook.github.io/jest/docs/tutorial-react.html) and the [React Native tutorial](https://facebook.github.io/jest/docs/tutorial-react-native.html) to get started with React or React Native codebases. You can use React's test renderer (`npm install --save-dev react-test-renderer`) to capture snapshots with Jest's snapshot feature and the `toMatchSnapshot` matcher:

```js
import renderer from 'react-test-renderer';
it('renders correctly', () => {
test('Link renders correctly', () => {
const tree = renderer.create(
<Link page="http://www.facebook.com">Facebook</Link>
).toJSON();
Expand All @@ -107,103 +85,14 @@ exports[`Link renders correctly 1`] = `
<a
className="normal"
href="http://www.facebook.com"
onMouseEnter={[Function bound _onMouseEnter]}
onMouseLeave={[Function bound _onMouseLeave]}>
onMouseEnter={[Function]}
onMouseLeave={[Function]}>
Facebook
</a>
`;
```

On subsequent test runs, Jest will compare the stored snapshot with the rendered output and highlight differences. If there are differences, Jest will ask you to fix your mistake and can be re-run with `jest -u` to update an outdated snapshot.

### Advanced Features

#### Use the interactive watch mode to automatically re-run tests

```
npm test -- --watch
// or
jest --watch
```

#### Install Jest globally

Jest can be installed globally: `npm install -g jest` which will make a global `jest` command available that can be invoked from anywhere within your project.

#### Async testing

Promises and even async/await can be tested easily.

Assume a `user.getUserName` function that returns a promise, now consider this async test with Babel and [`babel-plugin-transform-async-to-generator`](http://babeljs.io/docs/plugins/transform-async-to-generator/) or [`babel-preset-stage-3`](http://babeljs.io/docs/plugins/preset-stage-3/):

```js
import * as user from '../user';

// The promise that is being tested should be returned.
it('works with promises', () => {
return user.getUserName(5)
.then(name => expect(name).toEqual('Paul'));
});

it('works with async/await', async () => {
const userName = await user.getUserName(4);
expect(userName).toEqual('Mark');
});
```

Check out the [Async tutorial](https://facebook.github.io/jest/docs/tutorial-async.html) for more.

#### Only run test files related to changes with `jest -o`

On large projects and applications it is often not feasible to run thousands of tests when a single file changes. Jest uses static analysis to look up dependency trees in reverse starting from changed JavaScript files only. During development, it is recommended to use `jest -o` or `jest --onlyChanged` which will find tests related to changed JavaScript files and only run relevant tests.

#### Mocking and Sandboxing

Jest isolates test files into their own environment and isolates module execution between test runs. Jest swaps out `require()` and can inject mocks that were either [created manually](https://facebook.github.io/jest/docs/manual-mocks.html) by the user or automatically mocked through explicit calls to `jest.mock('moduleName')`.

#### Use `--bail` to abort after the first failed test.

If you don't want to wait until a full test run completes `--bail` can be used to abort the test run after the first error.

#### Use `--coverage` to generate a code coverage report

Code coverage can be generated easily with `--coverage`.

```
-----------------------|----------|----------|----------|----------|
File | % Stmts | % Branch | % Funcs | % Lines |
-----------------------|----------|----------|----------|----------|
react/ | 91.3 | 60.61 | 100 | 100 |
CheckboxWithLabel.js | 91.3 | 60.61 | 100 | 100 |
-----------------------|----------|----------|----------|----------|
```

#### Use `--json` for CI integrations

Jest can be integrated into Continuous Integration test runs and wrapped with other scripts to further analyze test results.

Example Output:

```js
{
"success": true,
"startTime": 1456983486661,
"numTotalTests": 1,
"numTotalTestSuites": 1,
"numRuntimeErrorTestSuites": 0,
"numPassedTests": 1,
"numFailedTests": 0,
"numPendingTests": 0,
"testResults":[
{
"name": "react/__tests__/CheckboxWithLabel-test.js",
"status": "passed",
"startTime": 1456983488908,
"endTime": 1456983493037
}
]
}
```
On subsequent test runs, Jest will compare the stored snapshot with the rendered output and highlight differences. If there are differences, Jest will ask you to fix your mistake and can be re-run with `-u` or `--updateSnapshot` to update an outdated snapshot.
<generated_getting_started_end />

## API & Configuration
Expand Down
79 changes: 79 additions & 0 deletions blog/2016-10-03-jest-16.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
---
title: Jest 16.0: Turbocharged CLI & Community Update
author: Christoph Pojer
authorURL: http://twitter.com/cpojer
authorFBID: 100000023028168
---

It's been one month since the last major release and we've made significant improvements to Jest since. In this major release we are updating the snapshot format we are using which will likely require snapshots to be updated when upgrading Jest. We don't make these changes lightly and don't expect this to happen often but we think it is necessary to improve the format from time to time.

## Upgraded CLI

![reporter](/jest/img/blog/16-reporter.gif)

Jest 16 features a new reporter interface that shows running tests as well as a live summary and a progress bar based on the estimated test runtime from previous test runs. We also improved the CLI output to work better with different color schemes. If there were test failures in a previous run, Jest will now always run those tests first to give useful signal to users as quickly as possible.

We also added a lot of new features which you may find useful:

* New CLI flags were added: A `--testNamePattern=pattern` or `-t <pattern>` option was added to filter tests from the command line much like `it.only` or `fit` does in tests.
* Previously failed tests now always run first.
* `jest <pattern>` is now case-insensitive to make it easier to filter test files.
* A test run in watch mode can now be interrupted. During a test run, simply press any of the keys used for input during watch mode (`a`, `o`, `p`, `q` or `enter`) to abort a test run and start a new one.
* The `--bail` flag now also works in watch mode. Together with running failed tests first, Jest's watch mode will now feel turbocharged!
* Jest now automatically considers files and tests with the `jsx` extension.
* Jest warns about duplicate manual mock files and we improved automatically created mocks for ES modules compiled with babel.
* A `jest.clearAllMocks` function was added to clear all mocks in between tests.
* We improved module resolution when `moduleNameMapper` is used.
* Finally, a `--findRelatedTests <fileA> <fileB>` cli option was added to run tests related to the specified files. This is especially helpful as a pre-commit hook if you'd like to run tests only on a specified set of files that have tests associated with them.

This is what Jest looks like when a test run is interrupted in watch mode:
![watch](/jest/img/blog/16-watch.gif)

## Snapshot Updates

Jest's snapshot implementation was completely rewritten. The new version of the `jest-snapshot` package is now structured in a way that allows for easier integration into other test runners and enables more cool integrations like with [React Storybook](https://voice.kadira.io/snapshot-testing-in-react-storybook-43b3b71cec4f#.qh4lzcadb). Jest doesn't mark snapshots as obsolete in a file with skipped or failing tests. We also made a number of changes to the snapshot format:

* Objects and Arrays are now printed with a trailing comma to minimize future changes to snapshots.
* We removed function names from snapshots. They were causing issues with different versions of Node, with code coverage instrumentation and we generally felt like it wasn't useful signal to show to the user that the name of a function has changed.
* Snapshots are now sorted using natural sort order within a file.

When upgrading to Jest 16, the diff might look similar to this one:
![snapshots](/jest/img/blog/16-snapshots.png)

## Test Library Updates

We finished the migration of Jasmine assertions to the new Jest matchers. We added three new matchers: `toBeInstanceOf`, `toContainEqual` and `toThrowErrorMatchingSnapshot` . We have more readable failure messages for the spy/mock matchers `toHaveBeenLastCalledWith`, `toHaveBeenCalledWith`, `lastCalledWith` and `toBeCalledWith`. Now that we have rewritten all assertions and separated them into their own package, we'll be working on making them standalone so they can be integrated into any test framework if you'd like to use them outside of Jest.

We also added a bunch of aliases that were requested by the community. To make Jest focus on a single test you can now use either `it.only` or `test.only` or keep using `fit`; For skipping a test, `it.skip` or `test.skip` are now available alongside of `xit`; finally to define a test as concurrent you can use `test.concurrent` which is useful in case your test accesses network resources or databases.

Finally, if you'd like to overwrite the `expect` global with a different assertion library like [chai](http://chaijs.com/), this can now be done using the `setupTestFrameworkScriptFile` configuration option.

## Community Update

Over the last month lots of articles were written about Jest's snapshot testing feature, how to migrate to Jest and how to get started writing tests. I also did a few live videos to explain how Jest and snapshot testing works:

* [FB Live Video about Snapshot Testing](https://www.facebook.com/react/videos/1035427199869020/).
* [JavaScript & React Testing with Kent C. Dodds](https://www.youtube.com/watch?v=i31VtyJSM-I&feature=youtu.be).

A number of people wrote articles about snapshot testing. The most opinionated article that resonated with the Jest team was “[Testing with Jest Snapshots: First Impressions](http://benmccormick.org/2016/09/19/testing-with-jest-snapshots-first-impressions/)”. Ben makes three great points in his blog post:

1. Snapshot tests are a complement for conventional tests not a replacement.
2. Snapshot tests are more useful with a healthy code review process.
3. Snapshot tests work well with auto-mocking.

We highly recommend reading the entire blog post. Ben did a fantastic job explaining the reasons why we built snapshot testing. It's important to point out that we didn't introduce snapshot testing to replace all other forms of testing but rather as a way to enable engineers to write tests for code that they otherwise wouldn't write tests for. It works well for things like React components, CLI output, error messages and many others but it doesn't solve all problems. Jest's goal is to provide many different ways to write effective tests without sacrificing performance or the project's maintainability.

Other highlights about snapshot testing:

* A React Native testing 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) 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#.putt9eipm).
* [How we landed on Jest snapshot testing for JavaScript](https://blog.grommet.io/post/2016/09/01/how-we-landed-on-jest-snapshot-testing-for-javascript).
* [Picture This: Snapshot Testing](http://guigrpa.github.io/2016/09/27/picture-this-snapshot-testing/).
* [Snapshot testing with React Storybook](https://voice.kadira.io/snapshot-testing-in-react-storybook-43b3b71cec4f).
* [Testing React and Redux Applications](https://medium.com/@ryancollinsio/testing-react-redux-applications-fee79ac0087f#.lyjl7st1n).
* If you are using the popular [enzyme](https://github.com/airbnb/enzyme) testing utility, there is now a project [enzyme-to-json](https://github.com/trayio/enzyme-to-json) which makes it possible to use Jest's snapshot testing feature together with enzyme.

[Redux itself now uses Jest](https://github.com/reactjs/redux/commit/7296d3cba1f5f899bdee5ef6695a8d21149f8d6c) and Max Stoiber wrote a [tutorial on how to test code written with redux](http://academy.plot.ly/react/6-testing/). There is also a great [guide on how to write tests for MobX](https://semaphoreci.com/community/tutorials/how-to-test-react-and-mobx-with-jest). If you are using [create-react-app](https://github.com/facebookincubator/create-react-app), Jest is now included by default. Kent C. Dodds created a ton of [videos on egghead.io](https://egghead.io/lessons/javascript-use-jest-s-snapshot-testing-feature?pl=testing-javascript-with-jest-a36c4074) that will help you get started with Jest.

If you are using other test runners, Kenneth Skovhus built an awesome [jest-codemods](https://github.com/skovhus/jest-codemods) library that will automate the conversion for you. Codemods are awesome: they'll allow you to quickly evaluate whether Jest will work for you. Give it a try!

The full [changelog can be found on GitHub](https://github.com/facebook/jest/blob/master/CHANGELOG.md#jest-1600). Jest 16 was a true JavaScript community effort and the project now has more than 220 contributors. We thank each and every one of you for your help to make this project great.
Loading

0 comments on commit 94238b0

Please sign in to comment.