Within a typescript project, I created a custom assertion for the chai assertion library like so:
// ./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`,
);
},
);
I use it this way:
require("../assertions/assertTimestamp");
import {expect} from "chai";
describe("My test", () => {
it("should test timestamp", () => {
expect(1610841600000).to.be.timestampOf("2021-01-16");
});
});
Yet I get typescript error:
TS2339:Property 'timestampOf' does not exist on type 'Assertion'.
I know I can workaround this issue via:
(expect(1610841600000).to.be as any).timestampOf("2021-01-16");
but I rather want to register my method within typescript, so that I also can make use of auto-completion within my IDE.