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

rob*_*kos 21 mocha.js node.js express sequelize.js

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

我知道before()函数.

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

Noa*_*oah 27

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

globalBefore.js

before(function(done) {
   // remove database data here
   done()
}) 
Run Code Online (Sandbox Code Playgroud)

单测试1.js

require('./globalBefore)
// actual test 1 here
Run Code Online (Sandbox Code Playgroud)

单测试2.js

require('./globalBefore)
// actual test 2 here
Run Code Online (Sandbox Code Playgroud)

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

测试原理

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

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

另请查看重新布线模块.它对于删除函数非常有效.


rob*_*lep 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() {
    ...
  });
});
Run Code Online (Sandbox Code Playgroud)

还有sequelize.sync({force: true}),将删除并重新创建所有表(.sync()描述在这里).