【发布时间】:2017-02-23 15:44:40
【问题描述】:
我有一个适用于 Node/PostgreSQL/Knex 的本地开发环境,因为我可以使用 API 发布到我机器上的开发数据库。我现在正在尝试为此功能创建测试,但出现错误。
这是我的配置:
//knexfile.js
module.exports = {
development: {
client: 'pg',
connection: {
host: '127.0.0.1',
user: 'dbUser',
password: 'dbpword',
port: 5432,
database: 'example-name'
},
migrations: {
directory: __dirname + '/db/migrations'
},
seeds: {
directory: __dirname + '/db/seeds/development'
}
},
}
//db.js
const config = require('../knexfile.js');
const env = process.env.NODE_ENV || 'development';
const knex = require("knex")(config[env]);
module.exports = knex;
knex.migrate.latest([config]);
然后是我的测试:
import chai from 'chai';
import { expect } from 'chai';
import chaiHttp from 'chai-http';
import knex from '../../db/db';
import app from '../../server';
chai.use(chaiHttp);
describe('Tokens API', () => {
beforeEach((done) => {
knex.migrate.rollback()
.then(() => {
knex.migrate.latest()
.then(() => {
return knex.seed.run()
.then(() => {
done();
});
});
});
});
afterEach((done) => {
knex.migrate.rollback()
.then(() => {
done();
});
});
describe('POST /users', () => {
it('posts a list of users to the database with all mandatory fields', (done) => {
chai.request(app)
.post('/users')
.send({
"users": [
"steve",
"whoever",
"matt",
"another"]})
.end((err, res) => {
expect(err).to.be.null;
expect(res).to.have.status(200);
expect(res).to.be.json;
done();
});
});
});
});
当我运行它时,我两次收到以下错误 - 我认为是 beforeEach 块中的 knex 调用:
Knex:warning - Can't take lock to run migrations: Migration table is already locked
Knex:warning - If you are sure migrations are not running you can release the lock manually by deleting all the rows from migrations lock table: knex_migrations_lock
Unhandled rejection MigrationLocked: Migration table is already locked
我尝试了很多方法——包括清除 knex_migrations_lock 表。我在网上能找到的唯一支持是this 线程,它建议使用DELETE FROM Migrations_lock where id <> 0; 清除锁表,但是我的锁表只有一个is_locked 列为零值。
知道发生了什么吗?
编辑: 我刚刚意识到,如果你编辑掉所有的 knex 调用,测试实际上就通过了。这可能是因为我有效地调用了 knex 两次——一次来自db.js,一次间接通过server.js?如果是这种情况,我该如何避免这样做 - 因为我肯定需要调用 knex 设置以便 Node 运行它?
【问题讨论】:
标签: node.js postgresql mocha.js knex.js