我正在尝试编写一个测试用例来捕获错误“错误:请提供pitchWidth 和pitchHeight”。但是我似乎无法期望将投掷作为成功的测试。
代码:
mocha.describe('testValidationOfBadInputData()', function() { mocha.it('init game fails on pitch height', async() => { let t1location = './init_config/team1.json' let t2location = './init_config/team2.json' let plocation = './test/input/badInput/badPitchHeight.json' // let badFn = await validation.initGame(t1location, t2location, plocation) expect(await validation.initGame(t1location, t2location, plocation)).to.throw() }) })
输出:
1) testValidationOfBadInputData()
init game fails on pitch height:
Error: Please provide pitchWidth and pitchHeight
at Object.validatePitch (lib/validate.js:56:11)
at Object.initiateGame (engine.js:18:12)
at Object.initGame (test/lib/validate_tests.js:9:29)
其他尝试也失败了:
1)
expect(await validation.initGame(t1location, t2location, plocation)).to.throw(Error, 'Please provide pitchWidth and pitchHeight');
2)
expect(await validation.initGame.bind(t1location, t2location, plocation)).to.throw();
不确定我做错了什么,文档似乎并不明显。https://www.chaijs.com/api/bdd/#method_throw
async function initGame(t1, t2, p) { let team1 = await common.readFile(t1) let team2 = await common.readFile(t2) let pitch = await common.readFile(p) let matchSetup = engine.initiateGame(team1, team2, pitch) return matchSetup }
以上是我正在调用的函数。
通过执行以下操作,我能够创建正确的测试:
mocha.describe('testValidationOfBadInputData()', function() {
mocha.it('init game fails on pitch height', async() => {
let t1location = './init_config/team1.json'
let t2location = './init_config/team2.json'
let plocation = './test/input/badInput/badPitchHeight.json'
try{
await validation.initGame(t1location, t2location, plocation);
}catch(err){
expect(err).to.be.an('Error');
expect(err.toString()).to.have.string('Error: Please provide pitchWidth and pitchHeight')
}
})
})
正如马特所描述的,我试图在期望的函数中调用该函数。这需要一个异步函数(因为我正在使用等待)但随后失败了
UnhandledPromiseRejectionWarning: 错误:请提供 pitchWidth 和 pitchHeight
这让我想到将它放入 try catch 块中,然后处理我们返回的错误。
在 catch 块中;
期望输出是错误
期望(错误).to.be.an('错误');
将错误的字符串版本与预期输出匹配
期望(err.toString()).to.have.string('错误:我的错误')
这可能不是最好的解决方案。很高兴接受其他答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句