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
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>;
}
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With