我在一个Typescript项目中使用Chai.js.它工作正常,直到我尝试向chai添加自定义匹配器.
我是这样添加的:
chai.use(function(chai, util) {
chai.assertion.addMethod("failed", function () {
new chai.Assertion(this._obj.isFailed).to.be.true();
});
});
Run Code Online (Sandbox Code Playgroud)
它工作正常,但当我尝试转换这个表达式时:
expect(obj).to.have.failed();
Run Code Online (Sandbox Code Playgroud)
我明白了
错误TS2339:"断言"类型上不存在属性"失败".
有没有更好的方法来扩展chai匹配器,同时避免类型检查器错误?
谢谢
Tim*_*rry 11
更新@jiri-tobisek的回答:使用最新的@types/chai
软件包通过npm,使用简单的导入而不是引用注释,现在添加帮助器我需要包装扩充declare global
或者它们未被检测到.
这意味着,如果在普通.ts
文件中声明内联类型(例如,与自定义匹配器定义一起),我只需添加:
declare global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果我想将类型放在他们自己的类型定义文件(my-custom-matcher.d.ts
)中,我使用:
declare module 'chai' {
global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 7
您可以使用声明合并来"扩展" chai.d.ts中的Assertion接口.在您的示例中,您必须向项目添加包含以下声明的.d.ts文件(例如failed.d.ts):
declare module Chai {
interface Assertion {
failed():Assertion;
}
}
Run Code Online (Sandbox Code Playgroud)
这会将failed()方法添加到原始的Chai.Assertion接口.不要忘记在您的规范中引用它:
/// <reference path="typings/chai/chai.d.ts"/>
/// <reference path="failed.d.ts"/>
...
expect(obj).to.have.failed();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2269 次 |
最近记录: |