How to add typehint for custom chai assertion?

Viewed 432

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.

1 Answers

Within your assertTimestamp.ts you can add:

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

it will add your custom function while keeping the existing one in place.

If you run your test now it will fail, as expected, with:

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