Uncaught AssertionError:预期404等于200

问题描述 投票:0回答:1

我正在尝试在nodeJS中编写单元测试以测试登录/注销页面。但是,每当我启动npm测试时,它都会说:“先于” {root}中的钩子:未捕获的AssertionError:预期404等于200,我到处都看过,但是在类似问题上提到的解决方案并不能解决我的问题。

这是我的test.js文件代码:

const expect = require('chai').expect;
const app = require('../index.js');
const request = require('supertest');


const userCredentials = {
  email: '[email protected]',
  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;
node.js express mocha chai
1个回答
0
投票

我发现了我的错误,我在测试文件中输入了错误的路由,我将其更改为该路由,并且可以正常工作(希望这是正确的:):

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: '[email protected]',
  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: [email protected], 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);
    });
  });
© www.soinside.com 2019 - 2024. All rights reserved.