typescript - 如何为自定义 chai 断言添加 typehint?

标签 typescript unit-testing chai typescript-typings assertion

在 typescript 项目中,我为 chai 断言库创建了一个自定义断言,如下所示:

// ./tests/assertions/assertTimestamp.ts
import moment = require("moment");
import {Moment} from "moment";

const {Assertion} = require("chai");

const parseDateWithTime = (dateWithTime: string, format = "YYYY-MM-DD hh:mm:ss"): Moment => {
    return moment.utc(dateWithTime, format);
};

const formatTimestamp = (timestampInMs: number): string => {
    return moment.utc(timestampInMs).toISOString();
};

Assertion.addMethod("timestampOf", function (humanReadableDate: string, format = "YYYY-MM-DD hh:mm:ss") {
        const expectedValue = parseDateWithTime(humanReadableDate, format);
        const formatted = formatTimestamp(this._obj);

        new Assertion(this._obj)
            .to.eq(
            expectedValue.valueOf(),
            `\nEXPECTED: "${expectedValue.toISOString()}"\nGOT:      "${formatted}"\n`,
        );
    },
);

我这样使用它:

require("../assertions/assertTimestamp");
import {expect} from "chai";


describe("My test", () => {
   it("should test timestamp", () => {
     expect(1610841600000).to.be.timestampOf("2021-01-16");
   });
});

但是我收到 typescript 错误:

TS2339:Property 'timestampOf' does not exist on type 'Assertion'.

我知道我可以通过以下方式解决此问题:

(expect(1610841600000).to.be as any).timestampOf("2021-01-16");

但我更想在 typescript 中注册我的方法,这样我也可以在我的 IDE 中使用自动完成功能。

最佳答案

assertTimestamp.ts 中,您可以添加:

declare global {
    export namespace Chai {
        interface Assertion {
            timestampOf(date: string, format?: string): void;
        }
    }
}

它将添加您的自定义函数,同时保留现有函数。

如果您现在运行测试,它将如预期失败,并显示:

AssertionError: 
EXPECTED: "2021-01-16T00:00:00.000Z"
GOT:      "2021-01-17T00:00:00.000Z"
: expected 1610841600000 to equal 1610755200000
Expected :1610755200000
Actual   :1610841600000

关于typescript - 如何为自定义 chai 断言添加 typehint?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60635466/

相关文章:

unit-testing - EF 4.1代码中的UnitOfWork和GenericRepository模式是否是冗余的?

javascript - lit-element:无法获取对象数组以循环呈现输出

angular - 在 Angular 4 的 canactivate guard 中返回 observable inside observable

javascript - 将我的自定义图标添加到 ionic 2 actionSheet 的按钮

javascript - 当没有找到测试时,Mocha 会抛出一个错误。这能被压制吗?

php - Symfony 3 表单类型测试

reactjs - 为什么我的按钮在我的测试中未定义?

asynchronous - Chai测试.then内部是否抛出错误

typescript - 如何将模块(sinon,chai)公开为具有正确类型的全局变量?

typescript - 如何解决“只读<{}>”类型上不存在属性 'navigation'