Last Updated: September 30, 2021
· 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) => {  
  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.

  2. What does the before hook do?

    It truncates the courses table, and restarts its sequence columns (eg id) count.