を使用してhapijs
v17.2.3
います。また、私はhapiに非常に慣れていません.Node.jsとアサーションライブラリLab
の簡単なテストユーティリティを使用してコードをテストしようとしています.code
私のtest.jsファイルは次のとおりです。
'use strict';
var path = require('path');
var dotEnvPath = path.resolve('./.env');
require('dotenv').config({ path: dotEnvPath });
const Code = require('code');
const Lab = require('lab');
const lab = exports.lab = Lab.script();
const describe = lab.describe;
const it = lab.it;
const expect = Code.expect;
const Joi = require('joi');
const Hapi = require('hapi');
const app = require('../app');
const server = new Hapi.Server();
const getServer = async () => {
const server = new Hapi.Server();
// server.connection();
return server.register(app)
.then(() => server);
};
lab.experiment('signup testing in "/signup"', () => {
lab.test('Return true if the user can successfully signup', (done, flags) => {
const signUpData = {
method: 'POST',
url: '/signup',
payload: {
name: 'vulcan',
password: 'vulcan@123',
email: 'vulcan@gmail.com',
username: 'vulcan123',
dob: '12-08-1994'
}
};
getServer()
.then((server) => server.inject(signUpData))
.then((response) => {
flags.note(`demo test note`);
if (response) {
console.log(response.statusCode);
Code.expect(response.statusCode).to.equal(201);
Code.expect(payload).to.contain(['name', 'password', 'email', 'username', 'dob']);
}
done();
});
});
});
lab.experiment('1) login test ', () => {
lab.test('login has successfully done', (done) => {
const loginData = {
method: 'POST',
url: '/login',
payload: {
email: 'wrong email',
login_password: 'wrong password',
}
};
getServer()
.then((server) => {
server.inject(loginData)
})
.then((response) => {
Code.expect(response.statusCode).to.equal(200);
done();
});
});
});
私のテストコマンドは次のとおりです:lab --assert code --coverage -t 100
私のサインアップコントローラーは:
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) => {
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: request.payload.password,
email: request.payload.email,
username: request.payload.username.toLowerCase(),
referralName: request.payload.username + '@gg',
emailConfirmationToken: uuidv1(),
dob: request.payload.dob,
tnc: true
};
let data = await signupHelper.signUpUser(user, request);
if (data.statusCode === 201) {
if (request.payload.referredBy) {
let configureReferral = await signupHelper.configureReferral(request.payload.referredBy, data.userId);
if (configureReferral.statusCode === 200) {
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
}
}
request.yar.flash('success', 'Account created, Please Login');
return h.redirect('/login');
} else {
request.yar.flash('error', data.message);
return h.redirect('/signup');
}
} catch (error) {
logger.error(error);
return h.redirect('/signup');
}
}
};
私のログインコントロール:
exports.login = {
description: 'Post to the login page',
notes: 'Accepts two paramters email and password which got validation',
tags: ['api'],
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
crumb: {
key: 'crumb',
source: 'payload',
},
'hapi-auth-cookie': {
redirectTo: false
}
},
validate: {
payload: {
email: Joi.string().min(3).email().required(),
login_password: Joi.string().min(4).required()
},
failAction: (request, h, error) => {
request.yar.flash('error', error.details[0].message.replace(/['"]+/g, ''));
return h.redirect('/login').takeover();
}
},
handler: async (request, h) => {
try {
const next = request.query.next ? request.query.next : '/dashboard';
if (request.auth.isAuthenticated) {
return h.redirect(next);
}
let resultData = await loginHelper.findByCredentials(request.payload.email, request.payload.login_password);
if (resultData.statusCode === 200) {
request.cookieAuth.set(resultData.user);
return h.redirect(next);
} else {
request.yar.flash('error', resultData.message);
return h.redirect('/login');
}
} catch (error) {
logger.error(error);
request.yar.flash('error', error.message);
return h.redirect('/login');
}
}
};
これは、テストを実行したときのエラーです。
Socket server start initiated
Socket server started
Server started at https://127.0.0.1:8000
signup testing in "/signup"
✔ 1) Return true if the user can successfully signup (3615 ms)
1) login test
✖ 2) login has successfully done
(node:9708) UnhandledPromiseRejectionWarning: AssertionError [ERR_ASSERTION]: Invalid plugin options {
"plugin": {
"sock": {
"init": function (server, options) {\n
..........
..........
},
"register" [1]: -- missing --
}
}
[1] "register" is required
at new AssertionError (internal/errors.js:102:11)
at Object.exports.assert (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/node_modules/hoek/lib/index.js:517:11)
at Object.exports.apply (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/config.js:22:10)
at internals.Server.register (/home/jeslin/projects/hapi/gamergully/node_modules/hapi/lib/server.js:410:31)
at getServer (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:23:19)
at lab.test (/home/jeslin/projects/hapi/gamergully/test/tests-signup.js:115:9)
at Immediate.setImmediate [as _onImmediate] (/home/jeslin/projects/hapi/gamergully/node_modules/lab/lib/runner.js:628:31)
at runCallback (timers.js:810:20)
at tryOnImmediate (timers.js:768:5)
at processImmediate [as _immediateCallback] (timers.js:745:5)
(node:8764) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
(node:8764) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Mongo Database connected
テスト ケースを 1 つだけ実行すると、エラーは返されません。複数実行すると、このエラーが表示されます
このリンクをたどってこれを行いました