Skip to content

Commit

Permalink
Merge branch 'master' into drop-polyfill
Browse files Browse the repository at this point in the history
  • Loading branch information
cpojer authored Feb 17, 2017
2 parents 940df38 + 6ddd2e5 commit 1573225
Show file tree
Hide file tree
Showing 117 changed files with 2,757 additions and 922 deletions.
45 changes: 45 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,50 @@
## master

## 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: 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 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 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 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 error for invalid transform config.
* 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.
* New `--collectCoverageFrom` cli argument.
* New `--coverageDirectory` cli argument.
* 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 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 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 pretty-printing for asymmetric matchers.
* New RSS feed for Jest's blog.
* New typeahead to filter cached test names added to watch mode.
* New typeahead to filter file names added to watch mode (#2324).
* 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).

## jest 18.1.0

* Fixed console.log and fake timer behavior in node 7.3.
Expand Down
64 changes: 54 additions & 10 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,39 +28,83 @@ The core team will be monitoring for pull requests. When we get one, we'll run s
git checkout -b my_branch
```

2. Run `npm install`. We recommend that you use `npm` version 3 or later.
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`.
```sh
npm install
yarn install
```
3. If you've added code that should be tested, add tests. You
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
npm run watch
yarn run watch
```

4. If you've changed APIs, update the documentation.
5. Ensure the test suite passes via `npm test`. To run the test suite you
5. If you've changed APIs, update the documentation.
6. Ensure the test suite passes via `yarn test`. To run the test suite you
may need to install Mercurial (`hg`). On macOS, this can be done
using [homebrew](http://brew.sh/): `brew install hg`.
```sh
brew install hg # maybe
npm test
yarn test
```
6. If you haven't already, complete the CLA.
7. If you haven't already, complete the CLA.

### 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.

[Complete your CLA here.](https://code.facebook.com/cla)

### Bugs
## 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:

```sh
cd /path/to/your/Jest_clone/packages/jest-cli
yarn link
```

To build Jest:

```sh
cd /path/to/your/Jest_clone
# Do one of the following:
# Check out a commit from another contributor, and then
yarn run build
# Or, save your changes to Jest, and then
yarn test # which also builds Jest
```

To run tests in another project with the development build of Jest:

```sh
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 unlink `jest` on the command line from `jest-cli/bin/jest.js` in a development build:

```sh
yarn unlink jest-cli
```

## Bugs

### Where to Find Known Issues

Expand All @@ -78,7 +122,7 @@ Facebook has a [bounty program](https://www.facebook.com/whitehat/) for the safe
* Discord - [#jest](https://discordapp.com/channels/102860784329052160/103622435865104384) on [Reactiflux](http://www.reactiflux.com/)
### Code Conventions
## Code Conventions
* 2 spaces for indentation (no tabs).
* 80 character line length strongly preferred.
Expand Down
7 changes: 4 additions & 3 deletions circle.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@ test:
- cd website && npm run test

deployment:
production:
branch: /master/
website:
branch: master
owner: facebook
commands:
# generate docs website
# Deploy Jest website
- git config --global user.email "[email protected]"
- git config --global user.name "Website Deployment Script"
- echo "machine github.com login jest-bot password $GITHUB_TOKEN" > ~/.netrc
Expand Down
2 changes: 1 addition & 1 deletion docs/CLI.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ Show some helpful information, similar to this page.

Prints the test results in JSON. This mode will send all other test output and user messages to stderr.

### `--jsonOutputFile=<filename>`
### `--outputFile=<filename>`

Write test results to a file when the `--json` option is also specified.

Expand Down
118 changes: 62 additions & 56 deletions docs/ExpectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,21 +149,35 @@ test('randocall calls its callback with a number', () => {

### `expect.arrayContaining(array)`

`expect.arrayContaining(array)` matches any array made up entirely of elements in the provided array. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, this code checks that `rollDice` returns only valid numbers:
`expect.arrayContaining(array)` matches a received array which contains all of the elements in the expected array. That is, the expected array is a **subset** of the received array. Therefore, it matches a received array which contains elements that are **not** in the expected array.

You can use it instead of a literal value:

* in `toEqual` or `toBeCalledWith`
* to match a property in `objectContaining` or `toMatchObject`

```js
// Rolls n virtual dice
function rollDice(n) {
let answer = [];
for (let i = 0; i < n; i++) {
answer.push(Math.floor(Math.random() * 6 + 1));
}
return answer;
}
describe('arrayContaining', () => {
const expected = ['Alice', 'Bob'];
it('matches even if received contains additional elements', () => {
expect(['Alice', 'Bob', 'Eve']).toEqual(expect.arrayContaining(expected));
});
it('does not match if received does not contain expected elements', () => {
expect(['Bob', 'Eve']).not.toEqual(expect.arrayContaining(expected));
});
});
```

test('rollDice only returns valid numbers', () => {
expect(rollDice(100)).toEqual(expect.arrayContaining([1, 2, 3, 4, 5, 6]));
})
```js
describe('Beware of a misunderstanding! A sequence of dice rolls', () => {
const expected = [1, 2, 3, 4, 5, 6];
it('matches even with an unexpected number 7', () => {
expect([4, 1, 6, 7, 3, 5, 2, 5, 4, 6]).toEqual(expect.arrayContaining(expected));
});
it('does not match without an expected number 2', () => {
expect([4, 1, 6, 7, 3, 5, 7, 5, 4, 6]).not.toEqual(expect.arrayContaining(expected));
});
});
```

### `expect.assertions(number)`
Expand All @@ -184,52 +198,11 @@ test('prepareState prepares a valid state', () => {

The `expect.assertions(1)` call ensures that the `prepareState` callback actually gets called.

### `expect.stringContaining(string)`

##### available in Jest **19.0.0+**

`expect.stringContaining(string)` matches any string that contains the exact provided string.


### `expect.stringMatching(regexp)`

`expect.stringMatching(regexp)` matches any string that matches the provided regexp. You can use it inside `toEqual` or `toBeCalledWith` instead of a literal value. For example, let's say you want to test that `randomCoolNames()` only returns names that are cool:

```js
function randomCoolName() {
// Generate a last name
let lastName = (
'TRFGBNMPLZ'[Math.floor(Math.random() * 10)] +
'aeiou'[Math.floor(Math.random() * 5)] +
'mnbvxdstrp'[Math.floor(Math.random() * 10)]);
return 'Kevin ' + lastName;
}

function randomCoolNames() {
let answer = [];
for (let i = 0; i < 100; i++) {
answer.push(randomCoolName());
}
return answer;
}

test('randomCoolNames only returns cool names', () => {
// A reasonable proxy for whether a name is cool or not
let coolRegex = /^Kevin/;

expect(randomCoolNames()).toEqual(
expect.arrayContaining([
expect.stringMatching(coolRegex)
])
);
});
```

This example also shows how you can nest multiple asymmetric matchers, with `expect.stringMatching` inside the `expect.arrayContaining`.

### `expect.objectContaining(object)`

`expect.objectContaining(object)` matches any object that recursively matches the provided keys. This is often handy in conjunction with other asymmetric matchers.
`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.

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:

Expand All @@ -244,6 +217,39 @@ test('onPress gets called with the right thing', () => {
})
```

### `expect.stringContaining(string)`

##### available in Jest **19.0.0+**

`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.

You can use it instead of a literal value:

* in `toEqual` or `toBeCalledWith`
* to match an element in `arrayContaining`
* to match a property in `objectContaining` or `toMatchObject`

This example also shows how you can nest multiple asymmetric matchers, with `expect.stringMatching` inside the `expect.arrayContaining`.

```js
describe('stringMatching in arrayContaining', () => {
const expected = [
expect.stringMatching(/^Alic/),
expect.stringMatching(/^[BR]ob/),
];
it('matches even if received contains additional elements', () => {
expect(['Alicia', 'Roberto', 'Evelina']).toEqual(expect.arrayContaining(expected));
});
it('does not match if received does not contain expected elements', () => {
expect(['Roberto', 'Evelina']).not.toEqual(expect.arrayContaining(expected));
});
});
```

### `expect.addSnapshotSerializer(serializer)`

You can call `expect.addSnapshotSerializer` to add a module that formats application-specific data structures.
Expand Down
2 changes: 1 addition & 1 deletion docs/ManualMocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ describe('listFilesInDirectorySync', () => {
});
```

The example mock shown here uses [`jest.genMockFromModule`](/jest/docs/api.html#jestgenmockfrommodulemodulename)
The example mock shown here uses [`jest.genMockFromModule`](/jest/docs/jest-object.html#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
Expand Down
39 changes: 39 additions & 0 deletions docs/TimerMocks.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,45 @@ describe('infiniteTimerGame', () => {
});
});
```

## Run Timers to Time

Another possibility is use `jest.runTimersToTime(msToRun)`. When this API is called, all pending "macro-tasks" that have been queued via setTimeout() or setInterval(), and would be executed within msToRun milliseconds, 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
'use strict';

function timerGame(callback) {
console.log('Ready....go!');
setTimeout(() => {
console.log('Times up -- stop!');
callback && callback();
}, 1000);
}

module.exports = timerGame;
```

```javascript
it('calls the callback after 1 second via runTimersToTime', () => {
const timerGame = require('../timerGame');
const callback = jest.fn();

timerGame(callback);

// At this point in time, the callback should not have been called yet
expect(callback).not.toBeCalled();

// Fast-forward until all timers have been executed
jest.runTimersToTime(1000);

// Now our callback should have been called!
expect(callback).toBeCalled();
expect(callback.mock.calls.length).toBe(1);
});
```

Lastly, it may occasionally be useful in some tests to be able to clear all of
the pending timers. For this, we have `jest.clearAllTimers()`.

Expand Down
4 changes: 2 additions & 2 deletions docs/TutorialAsync.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ if a Promise throws and the error is not handled, the test will fail. `expect.as
```js
// Testing for async errors can be done using `catch`.
it('tests error with promises', () => {
expect.assertions(1)
expect.assertions(1); // to be sure that `Promise` rejected and `expect` has been called once
return user.getUserName(3)
.catch(e => expect(e).toEqual({
error: 'User with 3 not found.',
Expand All @@ -122,7 +122,7 @@ it('tests error with promises', () => {

// Or try-catch.
it('tests error with async/await', async () => {
expect.assertions(1)
expect.assertions(1); // to be sure that `await` throws error and `expect` has been called once
try {
await user.getUserName(2);
} catch (object) {
Expand Down
Loading

0 comments on commit 1573225

Please sign in to comment.