使用 Sequelize 构建、播种和销毁 PostgreSQL 以进行测试

Building, seeding and destroying PostgreSQL with Sequelize for testing

我正在尝试为每个测试自动构建、播种和销毁我的数据库。我正在使用 PostgreSQL、Mocha 和 Sequelize。

我找到了一个库:sequelize-fixtures,它让我走到了那里,但最终它非常不一致,偶尔会抛出约束错误:Unhandled rejection SequelizeUniqueConstraintError: Validation error,即使我没有对型号。

这是我进行测试的方式

const sequelize = new Sequelize('test_db', 'db', null, {
  logging: false,
  host: 'localhost',
  port: '5432',
  dialect: 'postgres',
  protocol: 'postgres'
})

describe('/auth/whoami', () => {
  beforeEach((done) => {
    Fixtures.loadFile('test/fixtures/data.json', models)
      .then(function(){
         done()
      })
  })

  afterEach((done) => {
    sequelize.sync({
      force: true
    }).then(() => {
      done()
    })
  })

  it('should connect to the DB', (done) => {
    sequelize.authenticate()
      .then((err) => {
        expect(err).toBe(undefined)
        done()
      })
  })

  it('should test getting a user', (done) => {
    models.User.findAll({
      attributes: ['username'],
    }).then((users) => {
      users.forEach((user) => {
        console.log(user.password)
      })
      done()
    })
  })
})

我的模型是这样定义的:

var Sequelize = require('sequelize'),
    db = require('./../utils/db')

var User = db.define('User', {
  username: {
    type: Sequelize.STRING(20),
    allowNull: false,
    notEmpty: true
  },
  password: {
    type: Sequelize.STRING(60),
    allowNull: false,
    notEmpty: true
  }
})

module.exports = User

错误日志:

Fixtures: reading file test/fixtures/data.json...
Executing (default): CREATE TABLE IF NOT EXISTS "Users" ("id"   SERIAL , "username" VARCHAR(20) NOT NULL, "password" VARCHAR(60) NOT NULL, "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL, "updatedAt" TIMESTAMP WITH TIME ZONE NOT NULL, PRIMARY KEY ("id"));
Executing (default): SELECT "id", "username", "password", "createdAt", "updatedAt" FROM "Users" AS "User" WHERE "User"."id" = 1 AND "User"."username" = 'Test User 1' AND "User"."password" = 'testpassword';
Executing (default): SELECT i.relname AS name, ix.indisprimary AS primary, ix.indisunique AS unique, ix.indkey AS indkey, array_agg(a.attnum) as column_indexes, array_agg(a.attname) AS column_names, pg_get_indexdef(ix.indexrelid) AS definition FROM pg_class t, pg_class i, pg_index ix, pg_attribute a WHERE t.oid = ix.indrelid AND i.oid = ix.indexrelid AND a.attrelid = t.oid AND t.relkind = 'r' and t.relname = 'Users' GROUP BY i.relname, ix.indexrelid, ix.indisprimary, ix.indisunique, ix.indkey ORDER BY i.relname;
Executing (default): INSERT INTO "Users" ("id","username","password","createdAt","updatedAt") VALUES (1,'Test User 1','testpassword','2016-04-29 23:15:08.828 +00:00','2016-04-29 23:15:08.828 +00:00') RETURNING *;
Unhandled rejection SequelizeUniqueConstraintError: Validation error

这一次有效,然后就再也没有了。有没有更稳健的方法让我在每次测试之前,从一个完全干净的数据库开始,让我填充测试数据进行操作?

This is the closest I have come to finding any kind of discussion/answer.


此外,如果有人也知道为什么我仍然得到 console.logs(),即使我有 logging: false,那将不胜感激。

您粘贴的错误似乎表明同一数据被多次插入,导致 id 列发生冲突。

我希望调用 sequelize.sync({force: true}) 会为您清除每个 运行 上的所有数据库表,但情况似乎并非如此。您可以尝试将调用移至 beforeEach 挂钩,以确保对 运行 的第一个测试也有一个新数据库。

在我正在处理的应用程序中,我们不会为每个测试重新同步数据库,而是在开始时执行一次,然后在测试之间 运行cating 表。我们使用如下所示的清理函数:

function cleanup() {
    return User.destroy({ truncate: true, cascade: true });
}

create 方法完成从 json 装置加载数据并将它们插入数据库的工作。

function create() {
    var users = require('./fixtures/user.json');
    return User.bulkCreate(users);
}

您可以通过省略 sequelize-fixtures 并自行处理事情来简化依赖关系并提高稳定性。

此外,一个不相关的建议:Sequelize 的方法 return 承诺 Mocha 可以本地处理,因此无需在测试和 setup/teardown 代码中使用 done 回调:

 it('should connect to the DB', () => {
   return sequelize.authenticate()
 })

如果承诺被拒绝,测试将失败。

此外,Mocha's docs 目前不建议使用箭头函数:

Passing arrow functions to Mocha is discouraged. Their lexical binding of the this value makes them unable to access the Mocha context, and statements like this.timeout(1000); will not work inside an arrow function.