skip to Main Content

I use mocha, chai, and chai-as-promised.
The test should fail, but it doesn’t, I don’t know what’s wrong, any suggestions?

const { describe, it } = require('mocha')
const chai = require('chai')
const { expect } = require('chai')
const chaiAsPromised = require('chai-as-promised')

chai.use(chaiAsPromised)

describe('test', () => {
    it('must be rejected', async () => {
        expect(Promise.resolve('success')).to.rejected
    })
})

Test Result

I tried to test a promise that should be rejected and the test should fail, but the test was successful

2

Answers


  1. "Promise.resolve() resolves a promise, which is not the same as fulfilling or rejecting the promise." (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/resolve)

    If you want to write a ‘dummy test’ just too see if you can catch that a promise is rejected do something like:

    let promise = new Promise((resolve, reject) => reject('Failure'));
    expect(promise).to.eventually.be.rejectedWith('Failure');
    
    Login or Signup to reply.
  2. From the Chai as Promised docs

    Notice: either return or notify(done) must be used with promise assertions. This can be a slight departure from the existing format of assertions being used on a project or by a team. Those other assertions are likely synchronous and thus do not require special handling.

    The most powerful extension provided by Chai as Promised is the eventually property. With it, you can transform any existing Chai assertion into one that acts on a promise

    You can use async / await or .then(() => {}) to include multiple promises in a test.

    These four tests will fail:

    const { describe, it } = require('mocha');
    const chai = require('chai');
    const { expect } = require('chai');
    const chaiAsPromised = require('chai-as-promised');
    
    chai.use(chaiAsPromised);
    
    describe('test1', () => {
      it('must be rejected (1)', () => {
        return expect(Promise.resolve('success')).to.eventually.be.rejected;
      });
    });
    
    describe('test2', () => {
      it('must be rejected (2)', (done) => {
        expect(Promise.resolve('success')).to.eventually.be.rejected.notify(done);
      });
    });
    
    describe('test3', () => {
      it('must be rejected (3)', async () => {
        await expect(Promise.resolve('success1')).to.eventually.be.fulfilled;
        return expect(Promise.resolve('success2')).to.eventually.be.rejected;
      });
    });
    
    describe('test4', () => {
      it('must be rejected (4)', () => {
        return expect(Promise.resolve('success1')).to.eventually.be.fulfilled.then(
          () => expect(Promise.resolve('success2')).to.eventually.be.rejected
        );
      });
    });
    

    Live example: https://stackblitz.com/edit/node-ooc3jh?file=index.js

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search