测试一个异步函数使用sinon和chai引发了异常

时间:2020-07-15 15:36:48

标签: javascript node.js chai sinon sinon-chai

我有此导出功能:

module.exports.doThing = async (input) => {
  if(input === '') { throw('no input present') }
  // other stuff
  return input
}

以及一个测试文件,我试图在其中测试输入无效时是否引发了错误。这是我尝试过的:

const testService = require('../services/testService.js')
const chai = require('chai')
const expect = chai.expect
const sinon = require('sinon')
chai.use(require('sinon-chai'))

describe('doThing', () => {
  it('throws an exception if input is not present', async () => {
    expect(testService.doThing('')).to.be.rejected
  })
})

我遇到了错误Error: Invalid Chai property: rejectedUnhandledPromiseRejectionWarning

如何解决此测试?

1 个答案:

答案 0 :(得分:1)

您可以安装插件chai-as-promised。这使您可以执行以下操作:

const testService = require('../services/testService.js')
const chai = require('chai')
    .use(require('chai-as-promised'))
const expect = chai.expect;

describe('doThing', () => {
    it('throws an exception if input is not present', async () => {
        await expect(testService.doThing('')).to.be.rejectedWith('no input present');
    });
    it('should not throw ...', async () => {
        await expect(testService.doThing('some input')).to.be.fulfilled;
    });
})
相关问题