Last Updated: September 30, 2021
·
3.609K
· Evgenia Karunus

Cleaning the database in-between Mocha tests with Pg-promise

describe('db truncation in before hook', () => {
  beforeEach('truncating db', () => {
    return db.none('TRUNCATE courses RESTART IDENTITY')
  });

  // in one test we insert data into our database
  it('inserting data into db', () => {
    return db.none('insert into courses (title) values (${title})', { title: 'hello' })
  });

  // in another test we check db is indeed been cleaned by the before hook
  it('not seeing data in the db', () => {
    return db.any('select * from courses').then((data) => {  
      expect(data).to.deep.equal([]);
    })
  });
});
  1. Why are we returning db.any/none promises from our tests?

    Because if Mocha sees a promise returned from the it block, it will wait till this promise gets resolved. Otherwise our tests would always be passing by not hitting expect at the right time.
    https://mochajs.org/#asynchronous-code

  2. What does the before hook do?

    It truncates the courses table, and restarts its sequence columns (eg id) count.
    https://www.postgresql.org/docs/9.1/static/sql-truncate.html