Skip to content

Instantly share code, notes, and snippets.

@NooNoo1337
Created November 9, 2021 16:12
Show Gist options
  • Save NooNoo1337/963420d2ea039fcd0c7ce338293a8bbe to your computer and use it in GitHub Desktop.
Save NooNoo1337/963420d2ea039fcd0c7ce338293a8bbe to your computer and use it in GitHub Desktop.
import * as path from 'path';
import { Builder, fixturesIterator, Loader, Parser, Resolver } from 'typeorm-fixtures-cli/dist';
import { Connection, getConnection, getRepository } from 'typeorm';
import { Injectable } from '@nestjs/common';
interface QueryObject {
operationName: null | string;
query: string;
}
/**
* Class contains methods and helpers for tests
*/
@Injectable()
export class TestUtils {
get gqlPath() {
return '/graphql';
}
async loadDataBaseMocks(fixturesPath?: string): Promise<void> {
let connection: Connection;
const pathToFixtures = fixturesPath || path.resolve(__dirname, './fixtures');
try {
connection = await getConnection();
const loader = new Loader();
loader.load(path.resolve(pathToFixtures));
const fixtures = new Resolver().resolve(loader.fixtureConfigs);
const builder = new Builder(connection, new Parser());
for (const fixture of fixturesIterator(fixtures)) {
const entity = await builder.build(fixture);
await getRepository(entity.constructor.name).save(entity);
}
} catch (err) {
throw err;
}
}
async cleanDataBase() {
const { entityMetadatas } = await getConnection();
try {
for (const entity of entityMetadatas) {
const repository = await getRepository(entity.name);
await repository.query(`DELETE FROM ${entity.tableName};`);
}
} catch (error) {
throw new Error(`ERROR: Cleaning test db: ${error}`);
}
}
async closeDbConnection() {
const connection = await getConnection();
if (connection.isConnected) await connection.close();
}
getQueryObj(query: string): QueryObject {
return {
operationName: null,
query,
};
}
/**
* Converts js object and array into string for gql query
*/
convertObjectToJson(data: unknown): string {
return JSON.stringify(data).replace(/\"([^(\")"]+)\":/g, '$1:');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment