Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding chai.js matchers in Typescript

I'm using Chai.js in a Typescript project. It works fine until I try to add custom matchers to chai.

I'm adding it like this:

chai.use(function(chai, util) {
    chai.assertion.addMethod("failed", function () {
        new chai.Assertion(this._obj.isFailed).to.be.true();
    });
});

And it works fine, but when I try to transpile this expression:

expect(obj).to.have.failed();

I get

error TS2339: Property 'failed' does not exist on type 'Assertion'.

Is there a better way to extend the chai matchers while avoiding type-checker errors?

Thanks

like image 787
Amir Arad Avatar asked Sep 08 '15 08:09

Amir Arad


1 Answers

An update to @jiri-tobisek's answer: Using the up to date @types/chai package through npm, using simple imports instead of reference comments, to add helpers right now I need to wrap the augmentation in declare global or they're not detected.

That means, if declaring the types inline in a normal .ts file (e.g. alongside the custom matcher definition) I just add:

declare global {
    export namespace Chai {
        interface Assertion {
            responseText(expectedText: string): Promise<void>;
        }
    }
}

and if I want to put the types in their own type definition file (my-custom-matcher.d.ts), I use:

declare module 'chai' {
    global {
        export namespace Chai {
            interface Assertion {
                responseText(expectedText: string): Promise<void>;
            }
        }
    }
}
like image 126
Tim Perry Avatar answered Oct 04 '22 12:10

Tim Perry