gpt4 book ai didi

typescript - 如何为自定义 Chai 断言添加类型提示?

转载 作者:行者123 更新时间:2023-12-04 10:25:59 24 4
gpt4 key购买 nike

在 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 断言添加类型提示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60635466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com