Mocha mysql knex before each fails: Can't take lock to 运行 迁移

Mocha mysql knex before each fails: Can't take lock to run migrations

这是我的测试设置代码

const knex = require('../db').knex

beforeEach(() => knex.migrate.rollback()
  .then(() => knex.migrate.latest())
  .then(() => knex.seed.run())
)

afterEach(() => knex.migrate.rollback()
  .then(() => {})
)

得到如下错误

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

      1) "before each" hook for "is not allowed"
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
      2) "after each" hook for "is not allowed"

这里是db.js

const Knex = require('knex')
const Bookshelf = require('bookshelf')
const config = require('config')

var bookshelf = null
var knex = null

exports.init = () => {
  knex = Knex(config.get('database'))
  if (process.env.NODE_ENV !== 'test') {
    knex.migrate.latest()
  }

  bookshelf = Bookshelf(knex)
  bookshelf.plugin('registry')
  bookshelf.plugin('pagination')
  bookshelf.plugin('bookshelf-camelcase')
  bookshelf.plugin('visibility')

  exports.bookshelf = bookshelf
  exports.knex = knex

}

mocha.opts

--ui bdd
--slow 70
--growl
--recursive
--reporter spec

删除 migrations_lock table 中的所有行,然后重试。可能某些迁移已崩溃并保留了锁定。

此外,您不需要完成回调。只需返回 before/after 的承诺就足够了:

const knex = require('../db').knex

beforeEach(() => knex.migrate.rollback()
  .then(() => knex.migrate.latest())
  .then(() => knex.seed.run())
)

afterEach(() => knex.migrate.rollback())

编辑:

您的 db init 运行 knex.migrate.latest()并且在返回函数之前没有等待它完成。

exports.init = () => {
  knex = Knex(config.get('database'))
  if (process.env.NODE_ENV !== 'test') {
    // this starts running migrations and execution continues without waiting that this is ready 
    knex.migrate.latest() 
  }

  bookshelf = Bookshelf(knex)
  bookshelf.plugin('registry')
  bookshelf.plugin('pagination')
  bookshelf.plugin('bookshelf-camelcase')
  bookshelf.plugin('visibility')

  exports.bookshelf = bookshelf
  exports.knex = knex
}

事实证明 beforeEach 钩子因为 mysql 花费了很长时间。

使用 this.timeout 帮我解决了!

beforeEach(async function () {
  this.timeout(60 * 1000)
  await knex.migrate.rollback()
  await knex.migrate.latest()
  return knex.seed.run()
})