Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use chai-as-promised with Typescript?

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 ?

like image 669
Tchoupinax Avatar asked Nov 18 '18 18:11

Tchoupinax


People also ask

What is chai as promised?

Chai as Promised is an extension of that library specifically made to handle assertions with promises (as opposed to resolving them manually yourself).

What is done () in Chai?

notify(done) is hanging directly off of . should , instead of appearing after a promise assertion. This indicates to Chai as Promised that it should pass fulfillment or rejection directly through to the testing framework.


2 Answers

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');
like image 93
Frans Avatar answered Sep 20 '22 12:09

Frans


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)
like image 43
Fred Policarpo Avatar answered Sep 20 '22 12:09

Fred Policarpo