Jest Custom Matchers: "this" is undefined inside matcher

Viewed 171

In accordance with the documentation https://jestjs.io/docs/en/expect#custom-matchers-api I create my matcher, however this === undefined inside the matcher function. I want to use the helpers described in the documentation, such as this.isNot, but they are not available.

What could be the reason for this behavior?

setupJestExpect.ts:

expect.extend({
  toBeMoment(received: any): CustomMatcherResult {

    console.log(this); // undefined <-- here

    const pass: boolean = moment.isMoment(received) as boolean;
    return pass
      ? { pass, message: () => '' }
      : { pass, message: () => 'expected that received value to be an instance of Moment' };
  }
});

foo.spec.ts:

describe('Foo', () => {
  it('should do something', async (): Promise<void> => {
    // const data: any[] = ....
    expect(data).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          bar: expect.toBeMoment()
        })
      ])
    );
  });
});
1 Answers

The matcher is getting undefined in the execution context because of the way you are calling it.

If you call it with:

const m = moment();
expect(m).toBeMoment();

You receive the expected value in this.

Related