As part of my typescript project, I decided to create a custom assertion for the chai assertion library. Here is how I implemented it:
// ./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`,
);
},
);
This custom assertion can be used like this:
require("../assertions/assertTimestamp");
import {expect} from "chai";
describe("Testing timestamps", () => {
it("should validate timestamp conversion", () => {
expect(1610841600000).to.be.timestampOf("2021-01-16");
});
});
However, I encountered a typescript error:
TS2339:Property 'timestampOf' does not exist on type 'Assertion'.
To work around this issue, I found a temporary solution:
(expect(1610841600000).to.be as any).timestampOf("2021-01-16");
But my goal is to properly register this custom method within typescript so that I can benefit from auto-completion in my IDE.