3

I extend Chai with a helper in my TypeScript test.

import * as chai from 'chai';

chai.use((_chai) => {
  let Assertion = _chai.Assertion;
  Assertion.addMethod('sortedBy', function(property) {
    // ...
  });
});

const expect = chai.expect;

In the same file test case makes use of this method:

expect(tasks).to.have.been.sortedBy('from');

Compiler gives error that "Property 'sortedBy' does not exist on type 'Assertion'".

How can I add declaration of sortedBy to Chai.Assertion?

I've tried to add module declaration, just like other Chai plugin modules do, but it doesn't work.

declare module Chai {
  interface Assertion {
    sortedBy(property: string): void;
  }
}

I don't want to make the helper an individual module, because it's trivial.

1
  • @DanRevah I'm using tsd. My question is how to define my extension to the module. The method 'sortedBy' is not included in chai typings. Commented Feb 29, 2016 at 10:55

3 Answers 3

4

Try the following:

Extend chai in the chaiExt.ts like this:

declare module Chai 
{
    export interface Assertion 
    {
        sortedBy(property: string): void;
    }
}

Consume in chaiConsumer.ts:

import * as chai from 'chai';
//...
chai.expect(tasks).to.have.been.sortedBy('from');

[EDIT]

If you are using 'import' - you turn your file into the external module and declaration merging is not supported: link

Sign up to request clarification or add additional context in comments.

3 Comments

I know this way works. But I'm looking for a way to extend and declare it just in-place in my test file.
If you will use 'import' - you turn your file into the external module and declaration merging is not supported there: github.com/Microsoft/TypeScript/issues/2821
Thanks. The link explains why my declaration does't work. Let me spend more time to look into it.
0

Your code is correct. Modules and interfaces are opened by default on TS so you can redeclare and augment them.

Generally, what I do in cases like this is: I create a globals.d.ts file in the same folder as my project so the .d.ts will be automatically loaded, and then I'd add the type definition as you did.

declare module Chai {
  interface Assertion {
    sortedBy(property: string): void;
  }
} 

Comments

0

When I wanted to extend chai assertions, I needed to declare the interface slightly differently

declare global {
  namespace Chai {
    interface Assertion {
      sortedBy(property: string): void;
    }
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.