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

Closing server after mocha test, but data is still there

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

我希望每次测试套件运行时数据都是"restored",这样我就知道数组中的数据量。

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

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

谢谢。

 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;

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

我的解决方案(正如我在上面的评论中提到的)是将初始化 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)

这些绝不是详尽的测试,但它们会验证 users 在每次测试之前都已正确初始化。