在 Typescript 中添加 chai.js 个匹配器
Adding chai.js matchers in Typescript
我在 Typescript 项目中使用 Chai.js。它工作正常,直到我尝试将自定义匹配器添加到 chai。
我是这样添加的:
chai.use(function(chai, util) {
chai.assertion.addMethod("failed", function () {
new chai.Assertion(this._obj.isFailed).to.be.true();
});
});
它工作正常,但是当我尝试转换这个表达式时:
expect(obj).to.have.failed();
我明白了
error TS2339: Property 'failed' does not exist on type 'Assertion'.
有没有更好的方法来扩展 chai 匹配器,同时避免类型检查器错误?
谢谢
您可以使用 declaration merging to "extend" the Assertion interface in chai.d.ts。在您的示例中,您必须向项目添加一个包含以下声明的 .d.ts 文件(例如失败。d.ts):
declare module Chai {
interface Assertion {
failed():Assertion;
}
}
这将添加 failed() 方法到原来的Chai.Assertion 接口。
不要忘记在您的规范中引用它:
/// <reference path="typings/chai/chai.d.ts"/>
/// <reference path="failed.d.ts"/>
...
expect(obj).to.have.failed();
@jiri-tobisek 的回答更新:通过 npm 使用最新的 @types/chai
包,使用简单的导入而不是参考注释,现在添加助手我需要将扩充包装在 declare global
或者没有检测到。
这意味着,如果在普通 .ts
文件中声明内联类型(例如,与自定义匹配器定义一起),我只需添加:
declare global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
如果我想将类型放在它们自己的类型定义文件中 (my-custom-matcher.d.ts
),我使用:
declare module 'chai' {
global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
}
我在 Typescript 项目中使用 Chai.js。它工作正常,直到我尝试将自定义匹配器添加到 chai。
我是这样添加的:
chai.use(function(chai, util) {
chai.assertion.addMethod("failed", function () {
new chai.Assertion(this._obj.isFailed).to.be.true();
});
});
它工作正常,但是当我尝试转换这个表达式时:
expect(obj).to.have.failed();
我明白了
error TS2339: Property 'failed' does not exist on type 'Assertion'.
有没有更好的方法来扩展 chai 匹配器,同时避免类型检查器错误?
谢谢
您可以使用 declaration merging to "extend" the Assertion interface in chai.d.ts。在您的示例中,您必须向项目添加一个包含以下声明的 .d.ts 文件(例如失败。d.ts):
declare module Chai {
interface Assertion {
failed():Assertion;
}
}
这将添加 failed() 方法到原来的Chai.Assertion 接口。 不要忘记在您的规范中引用它:
/// <reference path="typings/chai/chai.d.ts"/>
/// <reference path="failed.d.ts"/>
...
expect(obj).to.have.failed();
@jiri-tobisek 的回答更新:通过 npm 使用最新的 @types/chai
包,使用简单的导入而不是参考注释,现在添加助手我需要将扩充包装在 declare global
或者没有检测到。
这意味着,如果在普通 .ts
文件中声明内联类型(例如,与自定义匹配器定义一起),我只需添加:
declare global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
如果我想将类型放在它们自己的类型定义文件中 (my-custom-matcher.d.ts
),我使用:
declare module 'chai' {
global {
export namespace Chai {
interface Assertion {
responseText(expectedText: string): Promise<void>;
}
}
}
}