Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a Jest custom matcher working in typescript?

I regularly have unit tests where I need to compare two moment objects. I'd us moment's built-in function moment.isSame(moment) to compare them. However, this means my assertion will look like this:

expect(moment1.isSame(moment2)).toBeTrue();

I didn't quite like this, especially because the failure message will be less informative. Hence, I wanted to write a custom jest matcher "toBeSameMoment". The following code seems to compile at least:

import moment from "moment";

declare global {
  namespace jest {
    interface MomentMatchers extends Matchers<moment.Moment> {
      toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
    }
  }
}

expect.extend({
  toBeSameMoment(received: moment.Moment, expected: moment.Moment): jest.CustomMatcherResult {
    const pass: boolean = received.isSame(expected);
    const message: () => string = () => pass ? "" : `Received moment (${received.toISOString()}) is not the same as expected (${expected.toISOString()})`;

    return {
      message,
      pass,
    };
  },
});

However, I can't really get it to work in my unit test... When I try the following test code:

import moment from "moment";
import "../jest-matchers/moment";

describe("Moment matcher", () => {

  test("should fail", () => {
    const moment1 = moment.utc();
    const moment2 = moment();

    expect(moment1).toBeSameMoment(moment2);
  });

});

...then I get the following error:

error TS2339: Property 'toBeSameMoment' does not exist on type 'JestMatchersShape<Matchers<void, Moment>, Matchers<Promise<void>, Moment>>'.

I don't quite get this error, though. For example, what is the void type this is referring to? I've tried googling about it, but didn't really find a good guide or so. I did take notice of this question: How to let know typescript compiler about jest custom matchers?, which seems to basically be a duplicate, but apparently not clear enough, yet.

I have jest types included in my tsconfig

like image 567
Martao Avatar asked Feb 14 '20 13:02

Martao


1 Answers

The other question and answer you linked to were correct, and you can also find a very succinct example for how to extend jest in this github comment on react-testing-library.

To implement their solution for your code, just change:

declare global {
  namespace jest {
    interface MomentMatchers extends Matchers<moment.Moment> {
      toBeSameMoment: (expected: moment.Moment) => CustomMatcherResult;
    }
  }
}

To:

declare global {
  namespace jest {
    interface Matchers<R> {
      toBeSameMoment(expected: moment.Moment): CustomMatcherResult;
    }
  }
}
like image 106
Joshua T Avatar answered Oct 21 '22 03:10

Joshua T