使用Mocha进行NodeJS测试。

时间:2017-10-25 18:58:32

标签: node.js mocha chai

我目前正在尝试使用Mocha和Chai测试应用程序,但是我很难将其中一个模块连接到测试中。

这是我的测试用例:

"use strict";

var chai = require('chai');
var expect  = require("chai").expect;
var helloWorld = require("../routes");
var mongoose = require("mongoose");  
var app = require("../app");
var application = require("../routes");

describe('helloWorld', function () {
  it('Mongo Module extended', function () {
    expect(helloWorld()).equal('Mongo Module Extended');
  });
});

describe('application', function application(app){
   it('connects properly', function(done) {
       expect(application(app))
        .request('http://localhost:80')
        .get('/')
        .end(function(err, res) {
            expect(res).to.have.status(200);
            done();                               // <= Call done to signal callback end
      });
   });      
});

这是我目前正在尝试测试的文件:

var passport = require('passport');
var Account = require('./models/account');
var path = require('path');
var mongojs = require('mongojs');
var dbx = mongojs('test', ['logs']);
var fs = require('fs');
var dbc = mongojs('test', ['accounts']);


 function helloWorld() {
          return 'Mongo Module Extended';
        }

module.exports = helloWorld;


 function application(app) {

    app.get('/',
        function(req, res){
            res.sendFile('login.html', {root: __dirname});
        });

    app.get('/login',
        function(req, res){
            res.sendFile(path.join(__dirname + '/login.html'));
        });

    app.get('/index', isLoggedIn,
        function(req, res){
            req.flash('info', 'Flash is back!')
            res.sendFile(path.join(__dirname + '/views/index.html'));
        });
    app.get('/', isLoggedIn,
        function(req, res){
            res.sendFile(path.join(__dirname + '/login.html'));
        });

   app.post('/login', function(req, res, next) {
        passport.authenticate('local', function(err, user, info) {
            if (err) {
                return next(err);
            }
            if (!user) {
                return res.json({success:false, message: "Wrong Username or Password"}); //sends json message to the Front end jQuery function
            }
            req.logIn(user, function(err) {
                if (err) {
                    return next(err);
                }
                res.json({success:true, redirectTo: '/index', message: "You are logged-in."}); //sends json message to the Front end jQuery function
            /* Add username and time of login to the collection in MongoDB */    
                dbc.accounts.findOne(function(err, info){
                      var users = info.username; //Gets the logging username from the collection
                      var date = new Date().toLocaleDateString(); // generates a new date.
                      console.log(date);

                      console.log(date +" "+ "date");
                      var stamp = {name: users, time:date};  // object to hold both variables.
                      //toLocaleDateString('en-GB')
                      dbx.logs.insert(stamp, function(err, result){ //query to insert one inside the "logs" collection.
                         if(err) { throw err; }else{console.log("added" + JSON.stringify(stamp));}
                      });
                  });
                /* END of Collection Logging Method */
            });
        })(req, res, next);
    });


   app.get('/logout',
        function(req, res){
            req.logout();
            res.redirect('/login');
        });


  function isLoggedIn(req, res, next) {     
        //console.log('here is Authenticated', req.isAuthenticated()) //prints out 'here is Authenticated' if the Passport login is successful
        if (req.isAuthenticated()){
            console.log('here is Authenticated');
            return next();
        }else{
            console.log("you cannot access the routes without being logged in!");
        }

    }

module.exports = application;

我一直收到这个错误:

  

TypeError:expect(...)。request不是函数

我猜这是我在我的应用程序文件中引用的第一个get请求:

app.get('/',
        function(req, res){
            res.sendFile('login.html', {root: __dirname});
        });

此时我不确定如何解决这个问题。我知道我的错误是我试图测试获取请求的方式,但我似乎无法绕过它。

如何更正我的代码,以便我可以正确引用GET方法POSTmodule.exports = application;方法?

1 个答案:

答案 0 :(得分:1)

柴自己并不支持测试http路线,你需要chai-http才能做到这一点。
您可以看到更多链接:https://scotch.io/tutorials/test-a-node-restful-api-with-mocha-and-chai