node.js - 验证错误: child "password" fails because ["password" is required]

标签 node.js chai hapi.js lab

验证错误:子“密码”失败,因为运行测试时显示[“密码”是必需的]错误

我使用 hapijs v17.2.3mongodb 作为后端。我正在尝试使用 labcode 执行单元测试。 这是我的tests.js

'use strict';

const Hapi = require('hapi');
const application = require('../app');
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const getServer = function () {
    const server = new Hapi.Server();
    server.connection();
    return server.register(application)
        .then(() => server);
};

 ......
 ......
 ......


lab.test('Simply test the unique route', (done) => {

    const signUpData = {
        method: 'POST',
        url: '/signup',
        payload: {
            name: 'vulcan',
            password: 'vulcan@123',
            verify: 'vulcan@123',
            email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceb8bba2adafa08ea9a3afa7a2e0ada1a3" rel="noreferrer noopener nofollow">[email protected]</a>',
            username: 'vulcan',
            referredBy: 'admin@gg',
            dob: '12/08/1994'
        }
    };

    getServer()
        .then((server) => server.inject(signUpData))
        .then((response) => {

            Code.expect(response.statusCode).to.equal(200);
            const payload = JSON.parse(response.payload);
            Code.expect(payload).to.exist();

            done();
        })
        .catch(done);
});

当我运行上面的代码时,出现以下错误

{ ValidationError: child "password" fails because ["password" is required]
    at Object.exports.process (/home/jeslin/projects/hapi/gamergully/node_modules/joi/lib/errors.js:196:19)
    at internals.Object._validateWithOptions (/home/jeslin/projects/hapi/gamergully/node_modules/joi/lib/types/any/index.js:675:31)
    at module.exports.internals.Any.root.validate (/home/jeslin/projects/hapi/gamergully/node_modules/joi/lib/index.js:146:23)
    at Object.internals.implementation [as cookie] (/home/jeslin/projects/hapi/gamergully/node_modules/hapi-auth-cookie/lib/index.js:95:25)
    at module.exports.internals.Auth._strategy (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/auth.js:52:47)
    at Object.register (/home/jeslin/projects/hapi/gamergully/lib/auth.js:6:116)
    at internals.Server.register (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/server.js:451:35)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:189:7)
    at Function.Module.runMain (module.js:696:11)
    at startup (bootstrap_node.js:204:16)
    at bootstrap_node.js:625:3
  isJoi: true,
  name: 'ValidationError',
  details:
   [ { message: '"password" is required',
       path: [Array],
       type: 'any.required',
       context: [Object] } ],
  _object:
   { password: undefined,
     cookie: 'GG-auth',
     isSecure: false,
     clearInvalid: true,
     ttl: 86400000,
     redirectTo: '/login',
     appendNext: true,
     redirectOnTry: false,
     isSameSite: 'Lax' },
  annotate: [Function] }

我不知道错误是什么,我浪费了很多时间来解决它

这是我的注册 Controller ,其中包含 joi

的所有验证
exports.postForm = {
    description: 'Submit the signup page',
    tags: ['api'],
    notes: 'accepts name password verify and email',

    auth: {
        mode: 'try',
        strategy: 'session'
    },
    validate: {
        payload: {
            name: Joi.string().required(),
            password: Joi.string().min(4).max(20).required(),
            verify: Joi.string().required(),
            email: Joi.string().email().required(),
            username: Joi.string().min(3).max(20).required(),
            referredBy: Joi.any(),
            dob: Joi.date().required().label('Date of Birth')
        },
        failAction: (request, h, error) => {
            // Boom bad request
            console.log('Validation Failed');
            request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
            return h.redirect('/signup').takeover();
        }
    },
    handler: async (request, h) => {
        try {

            ................

            ................

            var user = {
                name: request.payload.name,
                password: reques67t.payload.password,
                email: request.payload.email,
                username: request.payload.username,
                referralName: request.payload.username + '@gg',
                emailConfirmationToken: uuidv1(),
                dob: request.payload.dob
            };
            // Then save the user
            let data = await signupHelper.signUpUser(user, request);
            if (data.statusCode === 200) {

                if (request.payload.referredBy) {

                    request.yar.flash('success', 'Account created, Please Login');

                }
            } else {
                request.yar.flash('error', data.message);
                return h.redirect('/signup');
            }
        } catch (error) {
            console.log('error occired = ', error);

            return h.redirect('/signup');
        }
    }
};

最佳答案

我创建了一个简单的测试套件并且它通过了。我无法发现您的 joi 验证问题。

const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = require('code').expect;
const Joi = require('joi');
describe('Validator accountSetupToken checks', () => {

    let validation = Joi.object().keys({
        name: Joi.string().required(),
        password: Joi.string().min(4).max(20).required(),
        verify: Joi.string().required(),
        email: Joi.string().email().required(),
        username: Joi.string().min(3).max(20).required(),
        referredBy: Joi.any(),
        dob: Joi.date().required().label('Date of Birth')
    });

    it('Reject invalid payload', async () => {
        const result = Joi.validate({
            name: 'vulcan',
            password: 'vulcan@123',
            verify: 'vulcan@123',
            email: '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5325263f30323d13343e323a3f7d303c3e" rel="noreferrer noopener nofollow">[email protected]</a>',
            username: 'vulcan',
            referredBy: 'admin@gg',
            dob: '12/08/1994'
        }, validation, {abortEarly: false});
        expect(result.error).to.null();
        expect(result.error).to.not.exist();
    });

});

这是结果。

> lab --coverage-exclude test/data -m 5000n -a code -P "simple" "test/validators"


  .

1 tests complete
Test duration: 13 ms
Assertions count: 2 (verbosity: 2.00)
No global variable leaks detected

但是后来我在你的异常消息中看到了这个

details:
   [ { message: '"password" is required',
       path: [Array],
       type: 'any.required',
       context: [Object] } ],
  _object:
   { password: undefined,
     cookie: 'GG-auth',
     isSecure: false,
     clearInvalid: true,
     ttl: 86400000,
     redirectTo: '/login',
     appendNext: true,
     redirectOnTry: false,
     isSameSite: 'Lax' },
  annotate: [Function] }

密码字段似乎未定义,您确定您正在向路线发出有效的请求吗?

关于node.js - 验证错误: child "password" fails because ["password" is required],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54216512/

相关文章:

node.js - 显示最近发布的 npm 包版本,包括 beta 版本

angularjs - 将失败消息分配给期望调用

javascript - 如何将测试用例组织成大型应用程序的测试套件

javascript - 身份验证策略简单使用未知方案 : bearer-access-token

node.js - hapijs 有过载保护之类的东西吗?

node.js - 基于 REST 的 API 服务应使用哪种身份验证机制?

node.js - NestJS - 基于一个属性有条件地验证主体

javascript - 使用 require ('some_module.js' 时运行脚本 - 好的做法吗?

javascript - module.exports = Promise.all 在测试中不起作用

javascript - 如何使用 hapi.js 读取已在浏览器中设置的 cookie