node.js - 未捕获的 AssertionError:预期 404 等于 200
问题描述
我正在尝试在 nodeJS 中编写一个单元测试来测试登录/注销页面。但是每次我启动一个 npm 测试时,它都会说:“{root}”中的“before all”钩子:未捕获的 AssertionError:预期 404 等于 200,我到处寻找,但在类似问题上提到的解决方案并没有解决我的问题。
这是我的 test.js 文件的代码:
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)
})
})
});
这是我的 index.js 文件:
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;
解决方案
我发现了我的错误,我在我的测试文件中放了一个错误的路线,我把它改成了那个并且它有效(希望这是正确的):
const expect = require('chai').expect;
const app = require('../index.js');
const request = require('supertest');
//let's set up the data we need to pass to the login method
const userCredentials = {
email: 'arthur.rimbaud@yahoo.fr',
password: 'tototata'
}
//now let's login the user before we run any tests
const authenticatedUser = request.agent(app);
before(function(done){
authenticatedUser
.get('/')
.send(userCredentials)
.end(function(err, response){
expect(response.status).to.equal(200);
done();
});
});
//this test says: make a POST to the /login route with the email: arthur.rimbaud@yahoo.fr, password: 'tototata'
//after the POST has completed, make sure the status code is 200
//also make sure that the user has been directed to the home page
describe('GET /', function(done){
//addresses 1st bullet point: if 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('/')
.expect(200, done);
});
//addresses 2nd bullet point: 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('/logout')
.expect(302, done);
});
});
推荐阅读
- python - 打印一个随机整数
- javascript - Visual Studio 代码中的消息
- java - yaml 到 java 对象,始终为空
- list - 如何计算pyspark数据框中一列列表中元素的频率?
- node.js - 在 Azure CI/CD 管道中使用 npm 工作区来构建 React Web 应用程序?
- javascript - Passport JS 无法读取未定义的属性(读取“初始化”)
- node.js - 调试器在 WSL1 ubuntu-dev-environment 中的 NodeJS 中不起作用?
- java - 如何使这个 for 循环反复遍历数组列表,直到达到条件?
- sql-server - SSMS Snippet - 多次使用 SurroundsWith 的选择
- c++ - 在原子布尔值上使用 compare_exchange_strong (C++)