Extending third party module that is globally exposed

后端 未结 3 1394
-上瘾入骨i
-上瘾入骨i 2020-12-05 17:57

I am trying to add a custom matcher to Jest in Typescript. This works fine, but I can\'t get Typescript to recognize the extended Matchers.

myMatcher.ts

3条回答
  •  执笔经年
    2020-12-05 18:38

    Answer by @AluanHaddad is almost correct, sans a few types. This one works:

    export {};
    
    declare global {
      namespace jest {
        interface Matchers {
          myMatcher: (received: string) => R;
        }
      }
    }
    
    function myMatcher(this: jest.MatcherUtils, received: string, expected: string): jest.CustomMatcherResult {
      const pass = received === expected;
      return {
        pass,
        message: (): string => `expected ${received} to be ${expected}`,
      }
    }
    
    expect.extend({
      myMatcher,
    });
    

    For a real-world example, see https://github.com/Quantum-Game/quantum-tensors/blob/master/tests/customMatchers.ts (and that the tests actually pass: https://travis-ci.com/Quantum-Game/quantum-tensors).

提交回复
热议问题