首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用sinon和chai测试异步函数引发异常

使用sinon和chai测试异步函数引发异常
EN

Stack Overflow用户
提问于 2020-07-15 23:36:48
回答 1查看 145关注 0票数 0

我有这个导出的函数:

代码语言:javascript
复制
module.exports.doThing = async (input) => {
  if(input === '') { throw('no input present') }
  // other stuff
  return input
}

以及它的一个测试文件,在这个文件中,我试图测试当输入无效时是否抛出错误。这是我尝试过的:

代码语言:javascript
复制
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

如何修复此测试?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-16 01:07:18

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

代码语言:javascript
复制
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;
    });
})
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62918555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档