扩展全局公开的第三方模块

Dyl*_*art 22 typescript jestjs

我正在尝试在Typescript中为Jest添加自定义匹配器.这工作正常,但我不能让Typescript识别扩展Matchers.

myMatcher.ts

export default function myMatcher (this: jest.MatcherUtils, received: any, expected: any): { pass: boolean; message (): string; } {
  const pass = received === expected;
  return {
    pass: pass,
    message: () => `expected ${pass ? '!' : '='}==`,
  }
}
Run Code Online (Sandbox Code Playgroud)

myMatcher.d.ts

declare namespace jest {
  interface Matchers {
    myMatcher (expected: any): boolean;
  }
}
Run Code Online (Sandbox Code Playgroud)

someTest.ts

import myMatcher from './myMatcher';

expect.extend({
  myMatcher,
})

it('should work', () => {
  expect('str').myMatcher('str');
})
Run Code Online (Sandbox Code Playgroud)

tsconfig.json

{
  "compilerOptions": {
    "outDir": "./dist/",
    "moduleResolution": "node",
    "module": "es6",
    "target": "es5",
    "lib": [
      "es7",
      "dom"
    ]
  },
  "types": [
    "jest"
  ],
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "node_modules",
    "dist",
    "doc",
    "**/__mocks__/*",
    "**/__tests__/*"
  ]
}
Run Code Online (Sandbox Code Playgroud)

在someTests.ts中,我收到错误

error TS2339: Property 'myMatcher' does not exist on type 'Matchers'
Run Code Online (Sandbox Code Playgroud)

我已多次阅读Microsoft文档,但我无法弄清楚如何使用全局可用类型(未导出)进行命名空间合并.

将它放在来自jest的index.d.ts中工作正常,但对于快速变化的代码库和多方扩展的类不是一个好的解决方案.

Alu*_*dad 22

好的,这里有一些问题

当源文件(.ts.tsx)文件和声明文件(.d.ts)文件都是模块解析的候选者时,就像这里的情况一样,编译器将解析源文件.

您可能有两个文件,因为您要导出值并修改全局对象的类型jest.但是,您不需要两个文件,因为TypeScript具有用于从模块中扩充全局范围的特定构造.也就是说,您只需要以下.ts文件即可

myMatcher.ts

// use declare global within a module to introduce or augment a global declaration.
declare global {
  namespace jest {
    interface Matchers {
      myMatcher: typeof myMatcher;
    }
  }
}
export default function myMatcher<T>(this: jest.MatcherUtils, received: T, expected: T) {
  const pass = received === expected;
  return {
    pass,
    message: () => `expected ${pass ? '!' : '='}==`
  };
}
Run Code Online (Sandbox Code Playgroud)

也就是说,如果你有这种情况,那么在同一个文件中执行全局变异和全局类型扩充是一个好习惯.鉴于此,我会考虑重写如下

myMatcher.ts

// ensure this is parsed as a module.
export {};

declare global {
  namespace jest {
    interface Matchers {
      myMatcher: typeof myMatcher;
    }
  }
}
function myMatcher<T>(this: jest.MatcherUtils, received: T, expected: T) {
  const pass = received === expected;
  return {
    pass,
    message: () => `expected ${pass ? '!' : '='}==`
  };
}

expect.extend({
  myMatcher
});
Run Code Online (Sandbox Code Playgroud)

someTest.ts

import './myMatcher';

it('should work', () => {
  expect('str').myMatcher('str');
});
Run Code Online (Sandbox Code Playgroud)


shu*_*son 6

一种简单的方法是:

customMatchers.ts

declare global {
    namespace jest {
        interface Matchers<R> {
            // 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
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

我的specs

import "path/to/customMatchers";

test('even and odd numbers', () => {
   expect(100).toBeDivisibleBy(2);
   expect(101).not.toBeDivisibleBy(2);
});
Run Code Online (Sandbox Code Playgroud)