使用 sinon 和 chai 测试异步函数抛出异常

test an async function has thrown an exception using sinon and 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: rejected 以及 UnhandledPromiseRejectionWarning

我该如何修复这个测试?

您可以安装插件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;
    });
})