vendredi 29 avril 2016

Building, seeding and destroying PostgreSQL with Sequelize for testing

I am trying to automate my database being built, seeded and destroyed for each test. I am using PostgreSQL, Mocha and Sequelize.

I found a library: sequelize-fixtures that has got me part way there, but ultimately it's very inconsistent and occasionally will throw constraint errors: Unhandled rejection SequelizeUniqueConstraintError: Validation error even though I do not have any validation on the model.

Here's how I am doing the tests

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()
    })
  })
})

This worked once, then never again. Is there a more robust way for me to, before every test, start with a completely clean DB for me to fill with test data to operate on?

This is the closest I have come to finding any kind of discussion/answer.


Additionally, if anyone also knows why I still get console.logs() even though I have logging: false on, that would be appreciated.

Aucun commentaire:

Enregistrer un commentaire