Search code examples
javascriptloopback

Loopback 4 empty database before a test


I want to empty the database before my acceptance test cases.

In my aircraft.controller.acceptance.ts I have

import { givenEmptyDatabase } from './helpers/database.helpers';
...
before(givenEmptyDatabase);
...
describe( ... ) { ... }

in database.helpers.ts I try to act according to the LoopBack 4 documentation

import {AircraftRepository} from '../../src/repositories';
import {testdb} from '../fixtures/datasources/testdb.datasource';

export async function givenEmptyDatabase() {
  await new AircraftRepository(testdb).deleteAll();
}

but it's never described what the testdb.datasource.ts should look like. I have tried to make it look similar to my regular db.datasource.ts, but I'm not sure what to export..

import {inject} from '@loopback/core';
import {juggler, AnyObject} from '@loopback/repository';
const config = require('./db.datasource.json');

export class DbDataSource extends juggler.DataSource {
  static dataSourceName = 'db';

  constructor(
    @inject('datasources.config.db', {optional: true})
    dsConfig: AnyObject = config
  ) {
    super(dsConfig);
  }
}

Solution

  • Got an answer from the @loopback/repository. testdb.datasource.ts should look like this:

    import { juggler } from '@loopback/repository';
    
    export const testdb: juggler.DataSource = new juggler.DataSource({
      name: 'db',
      connector: 'memory'
    });