Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add snapshot property matchers #6210

Merged
merged 5 commits into from
May 24, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions docs/ExpectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -1192,13 +1192,16 @@ test('this house has my desired features', () => {
});
```

### `.toMatchSnapshot(optionalString)`
### `.toMatchSnapshot(propertyMatchers, snapshotName)`
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it will be better to go with something like this:

### `.toMatchSnapshot(?propertyMatchers|snapshotName, ?snapshotName)`

Even though we explain this later


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

_Note: While snapshot testing is most commonly used with React components, any
serializable value can be used as a snapshot._
Expand Down
55 changes: 55 additions & 0 deletions docs/SnapshotTesting.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,61 @@ 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:

```javascript
it('will fail every time', () => {
const user = {
createdAt: new Date(),
id: Math.floor(Math.random() * 20),
name: 'LeBron James',
};

expect(user).toMatchSnapshot();
});

// Snapshot
exports[`will fail every time 1`] = `
Object {
"createdAt": 2018-05-19T23:36:09.816Z,
"id": 3,
"name": "LeBron James",
}
`;
```

For these cases, Jest allows providing an asymmetric matcher for any property.
These matchers are checked before the snapshot is written or tested, and then
saved to the snapshot file instead of the received value:

```javascript
it('will check the matchers and pass', () => {
const user = {
createdAt: new Date(),
id: Math.floor(Math.random() * 20),
name: 'LeBron James',
};

expect(user).toMatchSnapshot({
createdAt: expect.any(Date),
id: expect.any(Number),
});
});

// Snapshot
exports[`will check the matchers and pass 1`] = `
Object {
"createdAt": Any<Date>,
"id": Any<Number>,
"name": "LeBron James",
}
`;
```

## Best Practices

Snapshots are a fantastic tool for identifying unexpected interface changes
Expand Down
62 changes: 62 additions & 0 deletions integration-tests/__tests__/to_match_snapshot.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,65 @@ test('accepts custom snapshot name', () => {
expect(status).toBe(0);
}
});

test('handles property matchers', () => {
const filename = 'handle-property-matchers.test.js';
const template = makeTemplate(`test('handles property matchers', () => {
expect({createdAt: $1}).toMatchSnapshot({createdAt: expect.any(Date)});
});
`);

{
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

weird to use scopes here, although I get why you do it. why not just a descirbe around it and multiple tests instead?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

My thoughts as well - I was copying the style from the rest of the suite. I'll update the suite 👌

writeFiles(TESTS_DIR, {[filename]: template(['new Date()'])});
const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch('1 snapshot written from 1 test suite.');
expect(status).toBe(0);
}

{
const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch('Snapshots: 1 passed, 1 total');
expect(status).toBe(0);
}

{
writeFiles(TESTS_DIR, {[filename]: template(['"string"'])});
const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch(
'Received value does not match snapshot properties for "handles property matchers 1".',
);
expect(stderr).toMatch('Snapshots: 1 failed, 1 total');
expect(status).toBe(1);
}
});

test('handles property matchers with custom name', () => {
const filename = 'handle-property-matchers-with-name.test.js';
const template = makeTemplate(`test('handles property matchers with name', () => {
expect({createdAt: $1}).toMatchSnapshot({createdAt: expect.any(Date)}, 'custom-name');
});
`);

{
writeFiles(TESTS_DIR, {[filename]: template(['new Date()'])});
const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch('1 snapshot written from 1 test suite.');
expect(status).toBe(0);
}

{
const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch('Snapshots: 1 passed, 1 total');
expect(status).toBe(0);
}

{
writeFiles(TESTS_DIR, {[filename]: template(['"string"'])});
const {stderr, status} = runJest(DIR, ['-w=1', '--ci=false', filename]);
expect(stderr).toMatch(
'Received value does not match snapshot properties for "handles property matchers with name: custom-name 1".',
);
expect(stderr).toMatch('Snapshots: 1 failed, 1 total');
expect(status).toBe(1);
}
});
4 changes: 4 additions & 0 deletions packages/expect/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import type {
} from 'types/Matchers';

import * as utils from 'jest-matcher-utils';
import {iterableEquality, subsetEquality, getObjectSubset} from './utils';
import matchers from './matchers';
import spyMatchers from './spy_matchers';
import toThrowMatchers, {
Expand Down Expand Up @@ -223,7 +224,10 @@ const makeThrowingMatcher = (
getState(),
{
equals,
getObjectSubset,
isNot,
iterableEquality,
subsetEquality,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thoughts on exposing these to matchers and how?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe stick them in this.utils instead of directly on this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had the same thought, will move

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also needs to be doced, fwiw

utils,
},
);
Expand Down
13 changes: 13 additions & 0 deletions packages/jest-snapshot/src/State.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,4 +190,17 @@ export default class SnapshotState {
}
}
}

fail(testName: string, received: any, key?: string) {
this._counters.set(testName, (this._counters.get(testName) || 0) + 1);
const count = Number(this._counters.get(testName));

if (!key) {
key = testNameToKey(testName, count);
}

this._uncheckedKeys.delete(key);
this.unmatched++;
return key;
}
}
46 changes: 41 additions & 5 deletions packages/jest-snapshot/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,13 @@ const cleanup = (hasteFS: HasteFS, update: SnapshotUpdateState) => {
};
};

const toMatchSnapshot = function(received: any, testName?: string) {
const toMatchSnapshot = function(
received: any,
propertyMatchers?: any,
testName?: string,
) {
this.dontThrow && this.dontThrow();
testName = typeof propertyMatchers === 'string' ? propertyMatchers : testName;

const {currentTestName, isNot, snapshotState}: MatcherState = this;

Expand All @@ -61,12 +66,43 @@ const toMatchSnapshot = function(received: any, testName?: string) {
throw new Error('Jest: snapshot state must be initialized.');
}

const result = snapshotState.match(
const fullTestName =
testName && currentTestName
? `${currentTestName}: ${testName}`
: currentTestName || '',
received,
);
: currentTestName || '';

if (typeof propertyMatchers === 'object') {
const propertyPass = this.equals(received, propertyMatchers, [
this.iterableEquality,
this.subsetEquality,
]);

if (!propertyPass) {
const key = snapshotState.fail(fullTestName, received);

const report = () =>
`${RECEIVED_COLOR('Received value')} does not match ` +
`${EXPECTED_COLOR(`snapshot properties for "${key}"`)}.\n\n` +
`Expected snapshot to match properties:\n` +
` ${this.utils.printExpected(propertyMatchers)}` +
`\nReceived:\n` +
` ${this.utils.printReceived(received)}`;

return {
message: () =>
matcherHint('.toMatchSnapshot', 'value', 'properties') +
'\n\n' +
report(),
name: 'toMatchSnapshot',
pass: false,
report,
};
} else {
Object.assign(received, propertyMatchers);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This won't handle deep objects - should it be a deep merge instead?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch, i'll add an integration test for this as well

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any follow up for this?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

}
}

const result = snapshotState.match(fullTestName, received);
const {pass} = result;
let {actual, expected} = result;

Expand Down
2 changes: 2 additions & 0 deletions packages/jest-snapshot/src/plugins.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {
Immutable,
ReactElement,
ReactTestComponent,
AsymmetricMatcher,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@thymikee already handled all the hard stuff for me, thanks!

} = prettyFormat.plugins;

let PLUGINS: Array<Plugin> = [
Expand All @@ -27,6 +28,7 @@ let PLUGINS: Array<Plugin> = [
DOMCollection,
Immutable,
jestMockSerializer,
AsymmetricMatcher,
];

// Prepend to list so the last added is the first tested.
Expand Down
1 change: 0 additions & 1 deletion website/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@
"Watch more videos|no description given": "Watch more videos",
"Who's using Jest?|no description given": "Who's using Jest?",
"Jest is used by teams of all sizes to test web applications, node.js services, mobile apps, and APIs.|no description given": "Jest is used by teams of all sizes to test web applications, node.js services, mobile apps, and APIs.",
"More Jest Users|no description given": "More Jest Users",
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated but needed on master

"Talks & Videos|no description given": "Talks & Videos",
"We understand that reading through docs can be boring sometimes. Here is a community curated list of talks & videos around Jest.|no description given": "We understand that reading through docs can be boring sometimes. Here is a community curated list of talks & videos around Jest.",
"Add your favorite talk|no description given": "Add your favorite talk",
Expand Down