在mocha测试后关闭服务器,但数据仍然存在

时间:2015-05-31 18:35:54

标签: javascript node.js express mocha

我试图通过REST API测试一些数据。数据作为数组存储在项目中。

我希望数据能够恢复"每次测试套件运行时,我都知道数组中的数据量。

但是当我测试帖子时。插入的元素在下一个测试套件中,即使我在每次测试之前启动和停止服务器。

app.js需要用户数组,所以通过停止和启动服务器,我认为在每次测试之前我都会干净,但它并没有

Thansk。

 global.test = true;

    // Test server setup
    var app = require('../app');
    var testPort = 9999;
    var testServer;

    // Dependencies
    var should = require('should');
    var request = require('request');

    var baseUrl = 'http://localhost:9999/api';

    describe('RESTApi : GET Methods', function () {
        //Start the Server before the TESTS
        beforeEach(function (done) {

            testServer = app.listen(testPort, function () {
                console.log("Server is listening on: " + testPort);
                done();
            })
                .on('error', function (err) {
                    console.log(err);
                });
        });

        afterEach(function () {  //Stop server after the test
            testServer.close(function () {
                console.log("closing server");
            });
        });

     TEST here           

    });

    describe('RESTApi : POST Methods', function () {
        //Start the Server before the TESTS
        before(function (done) {

            testServer = app.listen(testPort, function () {
                console.log("Server is listening on: " + testPort);
                done();
            })
                .on('error', function (err) {
                    console.log(err);
                });
        });

        after(function () {  //Stop server after the test
            testServer.close(function () {
                console.log("closing server");
            });
        });

       TEST here

    });

------ App.js ----- 我知道REST api应该在它自己的文件夹中。 :)

var path = require('path');
        var bodyParser = require('body-parser');

        //For testing to delete the cached user array
        delete require.cache[require.resolve('./users')];

        var users = require('./users');
        var express = require('express');

        function findUser(users, email) {
            var result = users.filter(function(u) {
                return u.email === email;
            });
            if(result.length >= 1) {
                return result[0];
            }
            return undefined;
        }

        var app = express();

        app.use(bodyParser.json());
        app.use(bodyParser.urlencoded({ extended: false }));


        app.get("/api/users", function(req, res) {
            res.send(users);
        });

        app.get("/api/users/:email", function(req, res) {
            var user = findUser(users, req.params.email);
            if(!user) {
                return res.status(404).send({error: "user not found"});
            }
            res.send(user);
        });

        app.post("/api/users", function(req, res) {
            var user = req.body;
            if(findUser(users, user.email)) {
                return res.status(400).send({error: "user exist"});
            }
            users.push(user);
            res.send(user);
        });

        app.put("/api/users/:email", function(req, res) {
            var user = req.body;
            if(!findUser(users, req.params.email)) {
                return res.status(404).send({error: "user not found"});
            }
            if(!user) {
                return res.status(404).send({error: "no user provided"});
            }
            for(var i = 0; i < users.length; i += 1) {
                if(users[i].email === user.email) {
                    users[i].password = user.password;
                    break;
                }
            }
            res.send(user);
        });

        app.delete("/api/users/:email", function(req, res) {
            var user = findUser(users, req.params.email);
            if(!user) {
                return res.status(404).send({error: "user not found"});
            }
            for(var i = 0; i < users.length; i++) {
                if(users[i].email === req.params.email) {
                    users.splice(i, 1);
                    break;
                }
            }
            res.send(user);
        });

        app.all('*', function(req, res) {
            res.status(500).send(req.url + " not a valid");
        });

        if(global.activeTest === undefined){
            app.listen(3000, function() {
                console.log("Rest API started, listen on port 3000");
            });
        }

        module.exports = app;

2 个答案:

答案 0 :(得分:0)

看起来app.listen()是异步的,因此无论服务器是否停止,您的测试都会继续运行。我会把你的测试放在callback参数中。

答案 1 :(得分:0)

我的解决方案(正如我在上面的评论中提到的)将重构将users var初始化为单独函数的代码,可以在每次测试之前调用它。

var path = require('path');
var bodyParser = require('body-parser');
var express = require('express');
var clone = require('clone'); // <-- add `clone` as a dependency

var users;
function initUsers() {
  users = clone(require('./users'));
}

// ... the rest if your code, initializing express/adding route handlers

app.listen(3000, function() {
  console.log("Rest API started, listen on port 3000");
});

module.exports = exports = app;
exports.initUsers = initUsers;

users.js中使用此作为我的示例数据:

module.exports = [
  { email: 'email0', password: 'password0' },
  { email: 'email1', password: 'password1' },
  { email: 'email2', password: 'password2' },
  { email: 'email3', password: 'password3' },
  { email: 'email4', password: 'password4' },
  { email: 'email5', password: 'password5' },
  { email: 'email6', password: 'password6' },
  { email: 'email7', password: 'password7' },
  { email: 'email8', password: 'password8' },
  { email: 'email9', password: 'password9' }
];

我可以在每次测试前通过调用initUsers()成功进行测试,如下所示:

var app = require('../app');
var initUsers = require('../app').initUsers;

var should = require('should');
var request = require('request');

var baseUrl = 'http://localhost:3000/api';

describe('RESTApi', function() {

  describe('GET Methods', function () {

    beforeEach(function() {
      initUsers();
    });

    it('should get all users initially', function(done) {
      request(baseUrl + '/users', function(err, res) {
        var data = JSON.parse(res.body);
        data.length.should.equal(10);
        done();
      });
    });

    it('should remove user', function(done) {
      request.del(baseUrl + '/users/email1', function(err, res) {
        var data = JSON.parse(res.body);
        data.email.should.equal('email1');
        data.password.should.equal('password1');

        request(baseUrl + '/users', function(err, res) {
          var data = JSON.parse(res.body);
          data.length.should.equal(9);
          done();
        });

      });
    });

    it('should get all users again', function(done) {
      request(baseUrl + '/users', function(err, res) {
        var data = JSON.parse(res.body);
        data.length.should.equal(10);
        done();
      });
    });

  });

});

如您所见,我写了三个测试。

  1. 获取所有用户(验证初始计数为10)
  2. 删除用户(验证计数现在为9)
  3. 获取所有用户(验证计数现在再次为10)
  4. 这些绝不是详尽的测试,但他们验证users在每次测试之前都已正确初始化。