2
votes

I'm doing an integration test by making requests to my dev server by Supertest. But I have trouble with how to put data into the database. For example, before run GET test, I want to insert data to the database. But I even can't get a connection from TypeORM:

ConnectionNotFoundError: Connection "default" was not found.

If I even get the connection from TypeORM, how I wrap a test within transaction and rollback transaction after finish the test to make sure the integration test doesn't effect to a real database.

Basically, Is there any package that similar with factory_bot of Rails ?

describe("Templates", (): void => {
  describe("GET /api/v1/templates/{templateHash}", (): void => {
    let template: Template;
    beforeEach(
      async (): Promise<void> => {
        let templateService: TemplateService = new TemplateService();
        let connection: Connection = getConnection("default");
        template = new Template(Buffer.from(faker.random.words()), faker.random.uuid(), faker.system.fileName());
        await templateService.create(connection, template);
      },
    );
    it("should return a template", (done): void => {
      request(config.devEnvEndpoint)
        .get(`api/v1/templates/${template.templateHash}`)
        .set("Accept", "application/json")
        .expect(200)
        .end((err, response): void => {
          console.log(response);
          done();
        });
    });
  });
});

1

1 Answers

0
votes

It looks like typeorm is not picking up your config. I recommend using the ormconfig.json file and have two database configs - one for your development and one for testing.

By having two databases, you won't need to worry about transactions and can drop the database between tests. I suppose transactions would be faster but it really depends on your usecase (I noticed tests were much slower when making lots of connection.synchronize() calls).

Then you could use an environment variable to determine which connection to instantiate:

// db.ts
import { Connection, createConnection } from 'typeorm'

let connection: Connection | null = null

export async function getConnection() {
  if (connection) {
    return connection;
  }

  // DATABASE_CONFIG can be 'development' or 'test'
  // and should correspond to the connection names
  // in the ormconfig.json file
  connection = await createConnection(process.env.DATABASE_CONFIG);

  return connection;
}

export async function closeConnection() {
  await connection?.close();
}

Then you can set the environment variable and run your tests:

// DATABASE_CONFIG=test yarn test
import { getConnection, closeConnection } from './db'

let connection: Connection;

beforeAll(async () => {
  connection = await getConnection();
});

beforeEach(async () => {
  // Drop everything and recreate db
  await connection.synchronize(true);
});

afterAll(async () => {
  await closeConnection();
});

it('should create a connection', () => {
  expect(connection).toBeDefined();
})