'How to use the clone function in pg-mem?

I'm trying to use pg-mem with the pg-promise adapter for testing my database layer.

Initially I've tried fetching a fresh database for each test:

import { newDb } from 'pg-mem';
import {createTables} from './database';

export const getTestDatabase = async () => {
  const database = await newDb().adapters.createPgPromise();
  database.connect();
  await createTables(database);
  return database;
};

But then I get an annoying warning about duplicate database connections for each test:

WARNING: Creating a duplicate database object for the same connection

So I tried to use the backup and restore functions to return a restored database for each test:

import { newDb } from 'pg-mem';
import {createTables} from './database';

const mock = newDb();
let backup;
let database;
let databaseInitialized = false;

export const getTestDatabase = async () => {
  if (!databaseInitialized) {
    databaseInitialized = true;
    database = await mock.adapters.createPgPromise();
    database.connect();
    await createTables(database);
    backup = mock.backup();
  } else {
    backup.restore();
  }
  return database;
};

This mostly works, except that some of my tests alter the schema, at which point I get this error:

Context: Error: You cannot restore this backup: schema has been changed since this backup
has been created => prefer .clone() in this kind of cases

How do I use the clone function? I can't find any documentation.

What's the correct way to solve my problem?



Solution 1:[1]

You need to call database.synchronize() before calling mock.backup().

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 guedesvf