Skip to content

Instantly share code, notes, and snippets.

@robwise
Created March 13, 2017 01:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save robwise/1b36656e6ed7645ae33716dfb19fb60a to your computer and use it in GitHub Desktop.
Save robwise/1b36656e6ed7645ae33716dfb19fb60a to your computer and use it in GitHub Desktop.
Extend Jest Expect with Moment.js Matcher
import moment from 'moment';
import diff from 'jest-diff';
// see: https://facebook.github.io/jest/docs/expect.html#expectextendmatchers
expect.extend({
toEqualDate(unparsedReceived, unparsedExpected) {
const received = moment(unparsedReceived);
const expected = moment(unparsedExpected);
const receivedAsString = received.format('L');
const expectedAsString = expected.format('L');
const pass = received.isSame(expected);
const message = pass
? () =>
`${this.utils.matcherHint('.not.toBe')}\n\n` +
'Expected date to not be same date as:\n' +
` ${this.utils.printExpected(expectedAsString)}\n` +
'Received:\n' +
` ${this.utils.printReceived(receivedAsString)}`
: () => {
const diffString = diff(expectedAsString, receivedAsString, {
expand: this.expand,
});
return `${this.utils.matcherHint('.toBe')}\n\n` +
'Expected value to be (using ===):\n' +
` ${this.utils.printExpected(expectedAsString)}\n` +
'Received:\n' +
` ${this.utils.printReceived(receivedAsString)}${diffString ? `\n\nDifference:\n\n${diffString}` : ''}`;
};
return { actual: received, message, pass };
},
});
@jtomaszewski
Copy link

Here's a small open source lib we created for this: https://github.com/ailohq/jest-expect-moment . U might find it useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment