作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在 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");
});
});
TS2339:Property 'timestampOf' does not exist on type 'Assertion'.
(expect(1610841600000).to.be as any).timestampOf("2021-01-16");
最佳答案
在您的 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/
我是一名优秀的程序员,十分优秀!