Skip to content

Instantly share code, notes, and snippets.

@bendrucker
Created October 1, 2014 09:52
Show Gist options
  • Star 18 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bendrucker/cf298bf515d8b6fdcd05 to your computer and use it in GitHub Desktop.
Save bendrucker/cf298bf515d8b6fdcd05 to your computer and use it in GitHub Desktop.
Truncate data during tests with knex
'use strict';
var Promise = require('bluebird');
var knex = require('../../src/db').knex;
var tables = [
'organizations',
'campaigns',
'donors',
'pledges',
'payments'
];
function truncate () {
return Promise.each(tables, function (table) {
return knex.raw('truncate table ' + table + ' cascade');
});
};
function seed () {
return Promise.each(tables, function (table) {
return knex(table).insert(require('./seeds/' + table));
});
};
describe('Integration Tests', function () {
beforeEach(function () {
return truncate().then(seed);
});
afterEach(function () {
return truncate();
});
require('require-all')(__dirname + '/specs');
});
@demisx
Copy link

demisx commented Mar 11, 2015

Is not restarting identity after each truncate intentional?

@bennycode
Copy link

Thanks for sharing your integration test code!

It is also recommended to update the test database to the latest schema before running any test:

const config = require(`${process.cwd()}/knexfile`)[process.env.NODE_ENV]
const knex = require('knex')(config)

const {MyPOJO} = require('../src/MyPOJO')
const {Model} = require('objection')

beforeAll(async done => {
  await knex.migrate.latest()
  await knex(MyPOJO.tableName).truncate()
  Model.knex(knex)
  done()
})

@srghma
Copy link

srghma commented Dec 15, 2018

My solution, truncates all tables in schemas

// ./truncateSchemas.js

export async function truncateSchemas(
  knexClient,
  schemas
) {
  if (schemas.length < 1) {
    throw new Error(`Expected schemas be non-emtpy array, but got ${schemas}`)
  }

  await knexClient.raw(
    `
      DO
      $func$
      BEGIN
        EXECUTE
        (
          SELECT 'TRUNCATE TABLE ' || string_agg(format('%I.%I', table_schema, table_name), ', ') || ' RESTART IDENTITY CASCADE'
          FROM information_schema.tables
          WHERE table_schema IN (${schemas.map(x => `'${x}'`).join(', ')})
          AND table_type = 'BASE TABLE'
        );
      END
      $func$;
    `
  )
}
// jest.config.js
module.exports = {
  transform: {
    '^.+\\.jsx?$': 'babel-jest',
  },
  setupTestFrameworkScriptFile: '<rootDir>/jest/index.js',
  testPathIgnorePatterns:       ['/node_modules/'],
}
// jest/index.js

import knex from 'knex'
import { truncateSchemas } from './truncateSchemas'

const knexClient = knex({
  client: 'pg',
  connection: {
    user:     process.env.POSTGRES_USER,
    password: process.env.POSTGRES_PASSWORD,
    host:     process.env.POSTGRES_HOST,
    port:     process.env.POSTGRES_PORT,
    database: process.env.POSTGRES_DB,
  }
})

beforeEach(async () => {
  await truncateSchemas(knexClient, ['app_public', 'app_private', 'app_hidden'])
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment