All files / libs/kernel/testing/server/bed/src helpers.ts

0% Statements 0/51
0% Branches 0/1
0% Functions 0/1
0% Lines 0/51

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52                                                                                                       
import { Logger, type INestApplication } from '@nestjs/common';
import { padStart } from 'lodash-es';
import { DataSource, type QueryRunner } from 'typeorm';

import { toError } from '@amalia/ext/typescript';

const logger = new Logger('TestHelpers');

export const promiseWait = (time: number) =>
  new Promise((resolve) => {
    if (process.env['NODE_ENV'] !== 'test') {
      logger.error('This should only be used during testing!');
    }

    setTimeout(() => resolve(null), time);
  });

export const wrapWithTransaction = async <TResult>(
  app: INestApplication,
  callback: (queryRunner: QueryRunner) => Promise<TResult>,
) => {
  if (process.env['NODE_ENV'] !== 'test') {
    logger.error('This should only be used during testing!');
  }

  const queryRunner = app.get(DataSource).createQueryRunner();
  try {
    await queryRunner.connect();
    await queryRunner.startTransaction();
    await callback(queryRunner);
    await queryRunner.commitTransaction();
  } catch (err) {
    logger.error(toError(err).message, toError(err).stack);
    await queryRunner.rollbackTransaction();
    throw new Error('Test failed');
  } finally {
    await queryRunner.release();
  }
};

export const generateFakeUuid = (n: number = 0) => {
  const paddedN = padStart(`${n}`, 12, '0');
  return `00000000-0000-0000-0000-${paddedN}`;
};

const removeNewLines = (str: string) =>
  str.replaceAll(/\n\s/gu, ' ').replaceAll('\n', ' ').replaceAll(/\s+/gu, ' ').trim();

export const expectStringsEqualsIgnoringNewLines = (a: string, b: string) => {
  expect(removeNewLines(a)).toEqual(removeNewLines(b));
};