Sequelize in-memory sqlite tests isolated db?

Viewed 2489

I have the following tests where I am trying to exercise my db model against a sqlite in-memory database

describe(`task model`, () => {
  let Task, sandbox;
  beforeEach(() => (sandbox = createSandbox()));
  afterEach(() => sandbox.restore());
  beforeEach(async () => {
    const dbConnection = new Sequelize(`sqlite::memory:`, { logging: false });
    stub(dbConnectionModule, `dbConnection`).value(dbConnection);
    Task = require(`./models/task.js`).Task;
    await dbConnection.sync({ force: true });
  });
  describe(`create a task`, () => {
    let task;
    beforeEach(async () => {
      task = Task.build(taskData);
      await task.save();
    });
    it(`gets an id`, () => expect(task.id).to.not.be.empty);
    it(`shows up with a find all`, async () => {
      const tasks = await Task.findAll();
      expect(tasks).to.have.length(1);
    });
  });
});

I can verify the connection was newed up twice and yet my second test confusingly comes back with 2 tasks created.

It seems to be using the same db as on the first test!

I was under the impression that I would get a new in-memory db each time the Sequelize constructor is called for sqlite's in-memory db, am I misunderstanding something?

Alternately, how do I drop and recreate the database entirely for a new test?

Surprisingly, even the following after the sync doesn't seem to work

    for (const model of Object.values(dbConnection.models))
      model.destroy({ truncate: true });
1 Answers

Hihi,

What I did was to replace the database in the index file, not in the tests.

models/index.js
...

const sequelize = require('sequelize')

let sequelize;
if(process.env.NODE_ENV === 'test') {
    sequelize = new Sequelize('sqlite::memory:');
}
...

and in your tests just import as usual

const { Task } = require('./models/index.js');
describe(`task model`, () => {
  beforeEach(() => (sandbox = createSandbox()));
  describe(`create a task`, () => {
    let task;
    beforeEach(async () => {
      task = Task.build(taskData);
      await task.save();
    });
    it(`gets an id`, () => expect(task.id).to.not.be.empty);
    it(`shows up with a find all`, async () => {
      const tasks = await Task.findAll();
      expect(tasks).to.have.length(1);
    });
  });
});

You must/should implement a solution to init the database in every test you do.

Related