How to use chai-as-promised with Typescript?

9.9k Views Asked by At

I'm trying to use chai-as-promised package with TypeScript. First of all, the following code works well in simple JavaScript.

import * as chai from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

chai.use(chaiAsPromised);
const expect = chai.expect;

import * as sinon from 'sinon';

import { MyClass } from '.';

describe('Test my class', () => {
  let myClass: MyClass;

  beforeEach(() => {
    myClass = new MyClass();
   });

  it('Should render home', () => {
    const req = new RequestMock();
    const res = new ResponseMock();

    return expect(myClass.getHomePage(req, res)).to.be.fulfilled()
      .then((returnedValue) => {
        chai.expect(returnedValue).to.not.be.equal([]);
      });
  });
});

I have the following error with this code :

enter image dedscription here

... and it pointed to this :

interface PromisedTypeComparison {
    (type: string, message?: string): PromisedAssertion; // <<-- 
    instanceof: PromisedInstanceOf;
    instanceOf: PromisedInstanceOf;
}

I tested plenty of opportunity and it is the one where I am closest to the solution it seems to me.

I would like to use function of chai-as-promise like fullfulled, rejected... etc.

How can i make it ?

4

There are 4 best solutions below

0
On

Just import the default of chai-as-promised and everything will work:

import * as chai from 'chai'    
import chaiAsPromised from 'chai-as-promised'
chai.use(chaiAsPromised)
0
On

I think you are missing the '.eventually' or '.become' in the assertion. Try rewriting it as

expect(myClass.getHomePage(req, res)).to.eventually.be.fulfilled;
0
On

You can write this way

import { use as chaiUse } from 'chai';
import * as chaiAsPromised from 'chai-as-promised';

chaiUse(chaiAsPromised);

0
On

I think this answer is what you need:

Add the types for chai-as-promised and that should take care of the TypeScript errors:

npm install --save-dev @types/chai-as-promised

Worked for me. Before, I was getting "Property 'eventually' does not exist on type 'Assertion'."; after adding this everyone was happy :-)

I did have to change my import to a require.

Before:

import chaiAsPromised from 'chai-as-promised';

After:

import chaiAsPromised = require('chai-as-promised');