我有此导出功能:
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
如何解决此测试?
答案 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;
});
})