Extending third party module that is globally exposed

后端 未结 3 1400
-上瘾入骨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:41

    A simple way is:

    customMatchers.ts

    declare global {
        namespace jest {
            interface Matchers {
                // add any of your custom matchers here
                toBeDivisibleBy: (argument: number) => {};
            }
        }
    }
    
    // this will extend the expect with a custom matcher
    expect.extend({
        toBeDivisibleBy(received: number, argument: number) {
            const pass = received % argument === 0;
            if (pass) {
                return {
                    message: () => `expected ${received} not to be divisible by ${argument}`,
                    pass: true
                };
            } else {
                return {
                    message: () => `expected ${received} to be divisible by ${argument}`,
                    pass: false
                };
            }
        }
    });
    

    my.spec.ts

    import "path/to/customMatchers";
    
    test('even and odd numbers', () => {
       expect(100).toBeDivisibleBy(2);
       expect(101).not.toBeDivisibleBy(2);
    });
    

提交回复
热议问题