rokpoto.com
rokpoto.com

Reputation: 10728

Fail mocha test in catch block of rejected promise

How to fail the test in catch block of promise rejection when making http call using axios? Adding expectations, asserts, should expressions in catch block doesn't help. The test is passing.

I's run using .\node_modules\.bin\mocha

let chai = require('chai');
var expect = chai.expect;

var axios = require('axios')
var instance = axios.create({})

    describe('test', () => {

        context('test', () => {

        it('should succeed', () => {
            let url = 'url'
            instance.get(url)
                    .then(function(response) {
                        expect(response.data).not.to.be.null
                    } )
                    .catch(function(err) {
                        console.error(err.data) 
                        // should fail the test                                          
                    })


        })

        })
    })

Upvotes: 4

Views: 3877

Answers (1)

KarlR
KarlR

Reputation: 1615

If You want to verify my suggestions, replace url value with valid url (ex: https://google.com)

You can try several ways:

1) Using assert.fail()

const axios = require('axios');
const { assert, expect } = require('chai');

const instance = axios.create({})

describe('test', () => {
  context('test', () => {
    it('should succeed', () => {
      let url = 'abc'
      return instance.get(url)
        .then((res) => { 
          expect(res.data).not.to.be.null;
        })
        .catch((err) => {
          assert.fail('expected', 'actual', err);
        });
    });
  });
});

2) Using done() with error object

const axios = require('axios');
const { expect } = require('chai');

const instance = axios.create({})

describe('test', () => {
  context('test', () => {
    it('should succeed', (done) => {
      let url = 'abc'
      instance.get(url)
        .then((res) => { 
          expect(res.data).not.to.be.null;
          done();
        })
        .catch((err) => {
          done(err);
        });
    });
  });
});

3) Simply just throw an error :)

const axios = require('axios');
const { expect } = require('chai');

const instance = axios.create({})

describe('test', () => {
  context('test', () => {
    it('should succeed', () => {
      let url = 'abc'
      return instance.get(url)
        .then((res) => { 
          expect(res.data).not.to.be.null;
        })
        .catch((err) => {
          throw err;
        });
    });
  });
})

If You want to check if that method fails at all and You expect this, go that way (it requires chai-as-promised package):

const axios = require('axios');
const chai = require('chai');

chai.use(require('chai-as-promised'));
const instance = axios.create({})

describe('test', () => {
  context('test', () => {
    it('should succeed', () => {
      let url = 'abc'
      return chai.expect(instance.get(url)).to.be.rejected;
    });
  });
});

Upvotes: 5

Related Questions