Friday 21 June 2019

How do I prepare my database for tests using Jest and Knex.js?

I'm trying to write some integration tests for a RESTful API I am writing in Node.I want to setup a test database so that I can can call my API endpoints with Supertest and assert that the correct data is returned.My Jest global hooks are as follows:const knex = require('../../db/setup'); beforeEach(async () => { await knex.migrate.rollback(); await knex.migrate.latest(); await knex.seed.run(); }); afterEach(async () => { await knex.migrate.rollback(); }); The setup file is as follows:const { Model } = require('objection'); const Knex = require('knex'); const environment = process.env.NODE_ENV || 'development'; const configuration = require('./knexfile')[environment]; const knex = Knex(configuration); Model.knex(knex); I currently have two test suites, each with a single test, if I delete my test.sqlite3 file and then run my tests I get one passing test and one failing test, with the following error:SQLITE_ERROR: table `knex_migrations` already exists If I then run my tests again I receive a different error:MigrationLocked: update `knex_migrations_lock` set `is_locked` = 1 - SQLITE_BUSY: database is locked How can I get the database to reset correctly between tests, is there a better approach to doing this (e.g. is my attempt to reset the database between tests incorrect), should I be doing it on a per test suite basis instead?

Submitted June 21, 2019 at 03:02PM by MDTHLN

No comments:

Post a Comment