How to get a Jest custom matcher working in typescript?

旧时模样 提交于 2021-02-07 11:49:19

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/60227432/how-to-get-a-jest-custom-matcher-working-in-typescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!