在运行测试之前清理测试数据库

时间:2013-05-01 13:55:50

标签: node.js express mocha sequelize.js

在运行测试套件之前清理数据库的最佳方法是什么(是否存在npm库或推荐的方法)。

我知道before()函数。

我正在使用node / express,mocha和sequelize。

3 个答案:

答案 0 :(得分:26)

before功能与清理数据库时的功能差不多。如果您只需要清理数据库一次,即在运行所有测试之前,您可以在单独的文件中使用全局before函数

globalBefore.js

before(function(done) {
   // remove database data here
   done()
}) 

单测试1.js

require('./globalBefore)
// actual test 1 here

单测试2.js

require('./globalBefore)
// actual test 2 here

请注意,即使已经需要两次,globalBefore也只会运行一次

测试原则

尝试在测试中限制外部依赖项(如数据库)的使用。外部依赖性越少,测试越容易。您希望能够并行运行所有单元测试,并且共享资源(如数据库)会使这很困难。

看一下Google Tech关于编写可测试的javascript的讨论 http://www.youtube.com/watch?v=JjqKQ8ezwKQ

另请查看rewire模块。它非常适用于删除函数。

答案 1 :(得分:17)

我通常这样做(比如User模型):

describe('User', function() {
  before(function(done) {
    User.sync({ force : true }) // drops table and re-creates it
      .success(function() {
        done(null);
      })
      .error(function(error) {
        done(error);
      });
  });

  describe('#create', function() {
    ...
  });
});

还有sequelize.sync({force: true})会删除并重新创建所有表(.sync()被描述为here)。

答案 2 :(得分:0)

我让这个lib清理并导入测试装置。

这样,您可以导入灯具,测试然后清理数据库。

看看以下内容:

before(function (done) {
   prepare.start(['people'], function () {
      done();
   });
});

after(function () {
   prepare.end();
});

https://github.com/diogolmenezes/test_prepare