尝试运行我的测试时出现此错误:
UnhandledPromiseRejectionWarning: Unhandled promise rejection
(rejection id: 1): TypeError: Cannot read property 'body' of undefine
我只需要“验证码”获得真实的结果。我应用于我的代码的任何更改都给出了相同的结果,我尝试删除异步函数,但我仍然遇到同样的问题。
这是我的测试代码:
import proxyquire from 'proxyquire';
import assert from 'assert';
import chai from 'chai';
const expect = chai.expect;
const loggerStub ={
log:()=>{
return;
}
}
const lodashStub = ()=>{
result = undefined;
}
const validationStub = {
validation:()=>{
return Promise.resolve({
data:{
success:true
}
});
}
}
const req = {
body:{
captchaResponse: true
}
}
const res = {
status: (status) => {
return {
send: () => {
return;
}
}
}
}
describe('Probando captcha', ()=>{
describe('Validación de captcha', ()=>{
it('Captcha validado OK', (done)=>{
const captcha = proxyquire('../src/controllers/captcha',{
'../domain/captcha': validationStub,
'../core/logger': loggerStub,
'lodash': lodashStub
});
const next = () => {
console.log('llegó al next');
expect(captcha.validation()).to.be.true;
done();
}
setTimeout(() => {
captcha.validation(req, res, next);
}, 200);
});
});
});
这里是我的代码:
import { get } from "lodash";
import captcha from "../domain/captcha";
import logger from "../core/logger";
require("babel-polyfill");
const validation = async (req, res, next) => {
if (!req.body.captchaResponse) {
logger.log("info", "MISSING CAPTCHA PARAMETERS");
return res.status(422).send();
}
const captchaResponse = req.body.captchaResponse;
console.log(req.body.captchaResponse);
try {
const result = await captcha.validation(captchaResponse);
if (get(result, "data.success")) {
logger.log("info", "CAPTCHA VALIDATION OK");
next();
return;
} else {
logger.log("info", "FAIL CAPTCHA VALIDATION");
return res.status(422).send();
}
} catch (e) {
console.log(e);
logger.log("info", "ERROR CAPTCHA VALIDATION");
return res.status(422).send();
}
};
export default { validation };
我的package.json测试:
“test”:“mocha --compilers js:babel-register babel-polyfill ./test/ - 递归“
答案 0 :(得分:1)
next ()
定义中的以下行会导致问题
expect(captcha.validation()).to.be.true;
您需要在req, res, next
中添加captcha.validation()
,或者根本删除此行。
为什么?因为函数需要三个参数,并且因为它没有,所以在 req.body 上得到 undefined 。