首页 > 解决方案 > 使用 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: rejected,而且UnhandledPromiseRejectionWarning

我该如何解决这个测试?

标签: javascriptnode.jschaisinonsinon-chai

解决方案


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

推荐阅读