我正在努力改进现有项目的测试覆盖率,试图探索开玩笑的模拟可行性(说实话我是NodeJS的新手,来自Java背景)并且认为我对基础有了基本的了解它。但是,我遇到了一个问题,我仍然无法解决为什么开玩笑的行为方式。
我正在针对(handler.js)编写测试的示例实现:
'use strict';
const profileStore = require('./store/profile-store');
module.exports.invoke = (event, context, callback) => {
let id = context.id;
// profileStore.read returns a Promise
profileStore.read(id)
.then((profile) => onSuccess(profile))
.catch((err) => onErrorProfile(err));
function onSuccess(profile) {
callback(null, 'Found Profile: ' + profile.name);
};
function onErrorProfile(err) {
callback(null, 'Error finding Profile');
};
};
测试文件(handler.test.js)
const handlerImp = require('./handler');
let event = {};
const profileStore = require('./stores/profile-store');
jest.mock('./stores/profile-store');
test('1 - should expect error with missing profile', () => {
profileStore.read.mockImplementationOnce(() => Promise.reject('for some unexpected reason'));
function callback(err, resp) {
expect(resp).toEqual('Error finding Profile');
}
return handlerImp.invoke(event, null, callback)
});
test('2 - should expect result when profile is found', () => {
profileStore.read.mockImplementationOnce(() => Promise.resolve({name: 'Random Profile Name'}));
function callback(err, resp) {
expect(resp).toEqual('Found Profile: Random Profile Name');
}
return handlerImp.invoke(event, null, callback)
});
test('3 - should fail test when error messages mis-matched', () => {
profileStore.read.mockImplementationOnce(() => Promise.reject('for some unexpected reason'));
function callback(err, resp) {
expect(resp).toEqual('Unable to find Profile');
}
return handlerImp.invoke(event, null, callback)
});
从测试#1和#2我非常确定测试确认了幸福路径和异常情况正确。
然而,对于测试#3,即使jest检测到错误匹配的期望,测试仍然被视为PASS,也非常令人费解的是UnhandledPromiseRejectionWarning,此站点上的一些帖子指出了代码中的潜在错误,但是我很确定我的其他测试用例确认Promise.reject被捕获并在onErrorProfile()中处理。
(node:87160)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:3):错误:期望(收到).toEqual(预期)
期望值等于:
“无法找到个人资料”
收到:
“查找个人资料时出错”
PASS handler.test.js
✓应该预计错误的配置文件(6ms)
✓应该在找到个人资料时(1ms)预期结果
✓如果错误消息匹配(3ms)
,则应该测试失败测试套房:1次通过,共1次 测试:3次通过,共3次 快照:总共0 时间:0.791s,估计1s
希望有人可以指出我错过了什么。在此先感谢您的帮助。