【发布时间】:2016-08-25 04:18:38
【问题描述】:
我正在尝试自动为每个测试构建、播种和销毁我的数据库。我正在使用 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,那将不胜感激。
【问题讨论】:
-
您的模型是如何定义的? logging false 意味着 Sequelize 不会将 SQL 打印到控制台。在您的情况下,您应该启用日志以获取有关您的问题的所有信息。
-
@denisazevedo 我已经用我的模型定义和日志更新了我的帖子。我试图禁用日志记录,但由于某种原因它仍然会生成日志,所以我仍然可以看到它们。
标签: node.js postgresql testing mocha.js sequelize.js