这是我编写测试用例的函数。
exports.sendOTPParser = event => {
console.log('sendOTPParser');
event = event || {};
try {
const body = JSON.parse(event.body);
const phoneNumber = body.phonenumber;
if (typeof phoneNumber !== 'string') {
throw new Error('MalformedRequest');
}
event.phoneNumber = body.phonenumber;
return event;
} catch (error) {
console.log('Error in isEmailUniqueParser: %s', error.message);
throw new Error('MalformedRequest');
}
}
这是测试给定函数的mocha代码。但是,它没有捕获错误。怎么了?
var file = require('../src/auth/eventParsers');
var expect = require('chai').expect;
describe('sendOTPParserTest', function(){
var event1 = {"body": '{"phonenumber": 1234}'};
var event2 = {"body": '{"phonenumber": "1234"}'};
// event2.body.phonenumber = '12345';
// event1.body.phonenumber = 12345;
it('returnTest', function(){
var result1 = file.sendOTPParser(event1);
// var result2 = file.sendOTPParser(event2); expect(result2.phoneNumber).to.equal(JSON.parse(event2.body).phonenumber);
expect(result1).to.throw(Error);
});
});
输出:
bash-3.2$ mocha sendOTPParserTest.js
sendOTPParserTest
sendOTPParser
Error in isEmailUniqueParser: MalformedRequest
1) returnTest
0 passing (14ms)
1 failing
1) sendOTPParserTest returnTest:
Error: MalformedRequest
at
答案 0 :(得分:0)
Chai的throw
断言需要函数,而不是函数结果。
为了使其有效,您可以使用以下内容:
it('returnTest', function() {
expect(() => file.sendOTPParser(event1)).to.throw(Error);
});