Я пытаюсь написать модульный тест в nodeJS для проверки страницы входа / выхода. Но каждый раз, когда я запускаю тест npm, он говорит: «прежде чем все» подключиться к «{root}»: Uncaught AssertionError: ожидалось, что 404 будет равняться 200, я искал везде, но решения, упомянутые по аналогичным проблемам, не решили мою.
Вот мой код для теста. js file:
const expect = require('chai').expect;
const app = require('../index.js');
const request = require('supertest');
const userCredentials = {
email: 'arthur.rimbaud@yahoo.fr',
password: 'tototata'
}
const authenticatedUser = request.agent(app);
before(function(done){
authenticatedUser
.post('/login-register')
.send(userCredentials)
.end(function(err, response){
expect(response.status).to.equal(200);
expect('/home');
done();
});
});
describe('GET /users', function(done){
// the user is logged in we should get a 200 status code
it('should return a 200 response if the user is logged in', function(done){
authenticatedUser.get('/users')
.expect(200, done);
});
//if the user is not logged in we should get a 302 response code and be directed to the /login page
it('should return a 302 response and redirect to /login', function(done){
request(app).get('/users')
.expect('/login-register')
.expect(302, done);
});
it('Should fail validation', () => {
return request(api)
.post('/')
.send(badReq)
.then(res => {
expect(res.status).to.equal(400)
})
})
});
Вот мой индекс. js file:
const express = require('express');
const path = require('path');
const cookieSession = require('cookie-session');
const bcrypt = require('bcrypt');
const dbConnection = require('./database');
const { body, validationResult } = require('express-validator');
const app = express();
app.use(express.urlencoded({extended:false}));
// SET OUR VIEWS AND VIEW ENGINE
app.set('views', path.join(__dirname,'views'));
app.set('view engine','ejs');
// APPLY COOKIE SESSION MIDDLEWARE
app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2'],
maxAge: 3600 * 1000 // 1hr
}));
// DECLARING CUSTOM MIDDLEWARE
const ifNotLoggedin = (req, res, next) => {
if(!req.session.isLoggedIn){
return res.render('login-register');
}
next();
}
const ifLoggedin = (req,res,next) => {
if(req.session.isLoggedIn){
return res.redirect('/home');
}
next();
}
// END OF CUSTOM MIDDLEWARE
// ROOT PAGE
app.get('/', ifNotLoggedin, (req,res,next) => {
dbConnection.execute("SELECT `name` FROM `users` WHERE `id`=?",[req.session.userID])
.then(([rows]) => {
res.render('home',{
name:rows[0].name
});
});
});// END OF ROOT PAGE
// REGISTER PAGE
app.post('/register', ifLoggedin,
// post data validation(using express-validator)
[
body('user_email','Invalid email address!').isEmail().custom((value) => {
return dbConnection.execute('SELECT `email` FROM `users` WHERE `email`=?', [value])
.then(([rows]) => {
if(rows.length > 0){
return Promise.reject('This E-mail already in use!');
}
return true;
});
}),
body('user_name','Username is Empty!').trim().not().isEmpty(),
body('user_pass','The password must be of minimum length 6 characters').trim().isLength({ min: 6 }),
],// end of post data validation
(req,res,next) => {
const validation_result = validationResult(req);
const {user_name, user_pass, user_email} = req.body;
// IF validation_result HAS NO ERROR
if(validation_result.isEmpty()){
// password encryption (using bcrypt)
bcrypt.hash(user_pass, 12).then((hash_pass) => {
// INSERTING USER INTO DATABASE
dbConnection.execute("INSERT INTO `users`(`name`,`email`,`password`) VALUES(?,?,?)",[user_name,user_email, hash_pass])
.then(result => {
res.send(`your account has been created successfully, Now you can <a href="/">Login</a>`);
}).catch(err => {
// THROW INSERTING USER ERROR'S
if (err) throw err;
});
})
.catch(err => {
// THROW HASING ERROR'S
if (err) throw err;
})
}
else{
// COLLECT ALL THE VALIDATION ERRORS
let allErrors = validation_result.errors.map((error) => {
return error.msg;
});
// REDERING login-register PAGE WITH VALIDATION ERRORS
res.render('login-register',{
register_error:allErrors,
old_data:req.body
});
}
});// END OF REGISTER PAGE
// LOGIN PAGE
app.post('/', ifLoggedin, [
body('user_email').custom((value) => {
return dbConnection.execute('SELECT `email` FROM `users` WHERE `email`=?', [value])
.then(([rows]) => {
if(rows.length === 1){
return true;
}
return Promise.reject('Invalid Email Address!');
});
}),
body('user_pass','Password is empty!').trim().not().isEmpty(),
], (req, res) => {
const validation_result = validationResult(req);
const {user_pass, user_email} = req.body;
if(validation_result.isEmpty()){
dbConnection.execute("SELECT * FROM `users` WHERE `email`=?",[user_email])
.then(([rows]) => {
bcrypt.compare(user_pass, rows[0].password).then(compare_result => {
if(compare_result === true){
req.session.isLoggedIn = true;
req.session.userID = rows[0].id;
res.redirect('/');
}
else{
res.render('login-register',{
login_errors:['Invalid Password!']
});
}
})
.catch(err => {
if (err) throw err;
});
}).catch(err => {
if (err) throw err;
});
}
else{
let allErrors = validation_result.errors.map((error) => {
return error.msg;
});
// REDERING login-register PAGE WITH LOGIN VALIDATION ERRORS
res.render('login-register',{
login_errors:allErrors
});
}
});
// END OF LOGIN PAGE
// LOGOUT
app.get('/logout',(req,res)=>{
//session destroy
req.session = null;
res.redirect('/');
});
// END OF LOGOUT
app.use('/', (req,res) => {
res.status(404).send('<h1>404 Page Not Found!</h1>');
});
app.listen(3000, () => console.log("Server is Running..."));
module.exports = app;