【发布时间】:2017-09-25 19:09:01
【问题描述】:
我正在尝试在 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 ? '!' : '='}==`,
}
}
myMatcher.d.ts
declare namespace jest {
interface Matchers {
myMatcher (expected: any): boolean;
}
}
someTest.ts
import myMatcher from './myMatcher';
expect.extend({
myMatcher,
})
it('should work', () => {
expect('str').myMatcher('str');
})
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__/*"
]
}
在 someTests.ts 中,我得到了错误
error TS2339: Property 'myMatcher' does not exist on type 'Matchers'
我已多次阅读 Microsoft 文档,但不知道如何将命名空间与全局可用类型(未导出)合并。
将它从 jest 放入 index.d.ts 效果很好,但对于快速变化的代码库和多方扩展的类来说,这不是一个好的解决方案。
【问题讨论】:
标签: typescript jestjs