拒绝承诺的捕获块中的失败摩卡测试

时间:2018-08-26 17:06:18

标签: node.js mocha axios chai

使用axios进行http调用时,如何在承诺拒绝的catch块中使测试失败? 断言,如果catch块中的表达式无济于事,则添加期望。 测试通过了。

我正在使用 .\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                                          
                    })


        })

        })
    })

1 个答案:

答案 0 :(得分:1)

如果您想验证我的建议,请用有效的网址(例如:https://google.com)替换网址值

您可以尝试几种方法:

1)使用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)将done()与错误对象一起使用

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)只需抛出一个错误:)

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;
        });
    });
  });
})

如果您想检查该方法是否完全失败并且您希望这样做,请按照这种方式进行操作(它需要chai-as-promised软件包):

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;
    });
  });
});