mercredi 27 mai 2020

How to extend Jest methods?

I have read this great thread in order to add a toBeOneOf() method to my Jest tests: Logical OR for expected results in Jest . I thus wrote:

expect.extend({
  toBeOneOf(received: any, items: Array<any>) {
    const pass = items.includes(received);
    const message = () =>
      `expected ${received} to be contained in array [${items}]`;
    if (pass) {
      return {
        message,
        pass: true,
      };
    }
    return {
      message,
      pass: false,
    };
  },
});

declare global {
  namespace jest {
    interface Matchers<R> {
      toBeOneOf(items: Array<any>): CustomMatcherResult;
    }
  }
}

describe("Test stuff", () => {
  test("test specific stuff", () => {
    expect(foo()).toBeOneOf([1,2);
  });

Unfortunately, Typescript gives me the following error inside the declare global object:

  1. ES2015 module syntax is preferred over custom TypeScript modules and namespaces

  2. All declarations of 'Matchers' must have identical type parameters.

How to fix this?

Aucun commentaire:

Enregistrer un commentaire