Jest Matchers

Basic Matchers

Jest has a fairly extensive list of basic matchers, found here: Expect ยท Jest (jestjs.io)

A few main tripping points that you'll probably forget:

expect().toBe() // Checks if 2 objects are the same *instance*
expect().toEqual() // Checks if 2 objects have equal properties (preferable I think)

expect().toBeCloseTo() // use this for floating-point equality testing.

More advanced matchers

In some cases, we may want to use more advanced matching techniques when asserting certain responses.

For example, it may be beneficial to ignore the exact timestamp generated by a service response, but to simply assert that there is one.

We can used more advanced matchers (detailed here: The hidden power of Jest matchers | by Boris | Medium) to test the interesting elements of the response.

Examples:

// Expecting a date, but without any care for the contents
const comment = createComment('test content', 'author@me.com');
expect(comment).toEqual({
  createdAt: expect.any(Date),
  content: 'test content',
  author: 'author@me.com'
});
// Partial match an object on specific keys
const user = prepareUserInfo('test-user'); 
// user object is something like ... 
// {
//   id: 123,
//   name: 'test-user',
//   profile: {...},
//   passwordHash: '*****',
//   whatever: {...}
// }
// ... but for the test we are interested only in name and id
expect(user).toEqual(expect.objectContaining({
  id: 123,
  name: 'test-user'
}));
// Checking a mocked service was called, formatting an input argument exactly.
test('Sends an email with all the listed items present, separated by newlines', async () => {
    const sendMail = jest.fn();
    const testLines = [
        `This is item 1`,
        `This is another item`,
        `Oh wow, yet another item!`,
    ];
    await manage.sendLinesEmail(testLines);

    expect(sendMail).toHaveBeenCalledTimes(1);
    expect(sendMail).toHaveBeenCalledWith({
        from: expect.any(string),
        to: expect.any(string),
        subject: expect.stringContaining('Preconfigured subject line!'),
        text: expect.stringContaining(`\n${testLines.join('\n')}`),
    });
});