13

I am trying to use Chai Promise test but it show an error I am using docker.

Here a simple function

            let funcPromise = (n) => {
                return new Promise((resolve, reject) =>{
                    if(n=="a") {
                        resolve("success");
                    }else {
                        reject("Fail")
                    }
                })
            }

simple test

            import chai from 'chai';
            var chaiAsPromised = require('chai-as-promised');
            chai.use(chaiAsPromised);
            let expect = chai.expect;
            let assert = chai.assert;               

            it('connect: test promise', (done) => {
                let func = funcPromise("a");
                expect(func).to.eventually.equal("success"); // dont work
                expect(func).to.be.rejected; // dont work
            })

Error on terminal FileTest.spec.ts:43:25 - error TS2339: Property 'eventually' does not exist on type 'Assertion'.

storage/database/MongooseEngine.spec.ts:44:35 - error TS2339: Property 'rejected' does not exist on type 'Assertion'.

Rolly
  • 3,205
  • 3
  • 26
  • 35

1 Answers1

18

The error is TypeScript complaining that it doesn't know about the additions that chai-as-promised makes to the chai assertions.

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

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

You will also want to await any assertions made with chai-as-promised:

import chai from 'chai';
import chaiAsPromised from 'chai-as-promised';
chai.use(chaiAsPromised);
const expect = chai.expect;

const funcPromise = (n) => new Promise((resolve, reject) => {
  if (n === 'a') { resolve('success'); }
  else { reject('fail'); }
});

it('connect: test promise', async () => {
  await expect(funcPromise('a')).to.eventually.equal('success');  // Success!
  await expect(funcPromise('b')).to.be.rejected;  // Success!
});
Brian Adams
  • 43,011
  • 9
  • 113
  • 111
  • Can i ask you something? If i use done and done() like this `it( ... (done) => { ...other code... done() });` it throws `Error: Resolution method is overspecified. Specify a callback *or* return a Promise; not both.` If i omit `done()` at the end it throws `Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise` Do you know why? Or where i can read about it? – Rolly Apr 26 '19 at 15:21
  • [This section](https://mochajs.org/#asynchronous-code) is a good resource. That error means you are using `done` **and** returning a `Promise` (either by returning a `Promise` directly or by using an `async` test function). `Mocha` throws that error to let you know that doing both isn't necessary...pick whichever makes your test easier (I usually use an `async` function and call `await` on any `Promises` during the test) @roll – Brian Adams Apr 28 '19 at 05:01