无法通过mocha nodejs中要测试的函数指定抛出的错误。 expect.to.throw(错误)不起作用

时间:2017-04-04 10:56:09

标签: node.js mocha chai

这是我编写测试用例的函数。

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      

1 个答案:

答案 0 :(得分:0)

Chai的throw断言需要函数,而不是函数结果

为了使其有效,您可以使用以下内容:

it('returnTest', function() {
  expect(() => file.sendOTPParser(event1)).to.throw(Error);
});