我正在尝试编写一个捕获错误“错误:请提供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 }
上面是我正在调用的函数。
答案 0 :(得分:0)
我认为这看起来类似于我昨天遇到的一个问题,并且与此问题相符: Is node's assert.throws completely broken?
该函数在传递给Expect()之前正在堆栈中执行。
代替尝试
expect(function() { await validation.initGame(t1location, t2location, plocation); }).to.throw()
答案 1 :(得分:0)
通过执行以下操作,我可以创建正确的测试:
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')
}
})
})
正如Matt所描述的,我试图在期望的函数内调用该函数。这需要一个异步函数(因为我正在使用await),但随后失败了
UnhandledPromiseRejection警告:错误:请提供pitchWidth和 pitchHeight
这让我想到了将其放入try catch块中,然后处理返回的错误。
在catch块中;
期望输出错误
expect(err).to.be.an('Error');
将错误的字符串版本匹配到预期的输出
expect(err.toString())。to.have.string('错误:我的错误')
这可能不是最佳解决方案。很高兴获得其他答案。