Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit Testing in ts-jest with TypeOrm entities

Am trying to write tests, but am getting error. i think i have problem with connection. "Cannot execute operation on "default" connection because connection is not yet established."

i have tests folder, and in it am having user.spec.ts and testhelper.ts

testhelper.ts

// import { Connection, createConnection } from "typeorm";
import { DataSource, DataSourceOptions } from "typeorm";

import Database from "better-sqlite3";

export class TestHelper {
  private static _instance: TestHelper;

  private constructor() {}

  public static get instance(): TestHelper {
    if (!this._instance) this._instance = new TestHelper();

    return this._instance;
  }

  private dbConnect!: DataSource;
  private testdb!: any;
  async setupTestDB() {
    this.testdb = new Database(":memory:", { verbose: console.log });

    this.dbConnect = new DataSource({
      name: "default",
      type: "better-sqlite3",
      database: ":memory:",
      entities: ["src/entity/**/*.ts"],
      synchronize: true,
    } as DataSourceOptions);
  }

  teardownTestDB() {
    this.dbConnect.destroy();
    this.testdb.close();
  }
}

user.spec.ts

import { createUser } from "../src/controllers/user.controller";
//@ts-ignore
import { TestHelper } from "./testhelper";

beforeAll(async () => {
  await TestHelper.instance.setupTestDB();
});

afterAll(() => {
  TestHelper.instance.teardownTestDB();
});

describe("User Tests", () => {
  test("should create user", async () => {
    const body = {
      firstname: "John",
      lastname: "Brut",
      email: "[email protected]",
      password: "password123",
    };
    const res = {};
    //@ts-ignore
    const user = await createUser(body, res);
    //@ts-ignore
    expect(user.firstname).toBe("John");
    //@ts-ignore
    expect(user.lastname).toBe("Brut");
  });
});

I'm doing this first time. and am stuck on it very long time... can someone please help me with this... : (

like image 576
BasDriver Avatar asked Jan 18 '26 07:01

BasDriver


1 Answers

try this way, testhelper.ts

  async setupTestDB() {
    this.testdb = new Database(":memory:", { verbose: console.log });

    this.dbConnect = new DataSource({
      name: "default",
      type: "better-sqlite3",
      database: ":memory:",
      entities: ["src/entity/**/*.ts"],
      synchronize: true,
    } as DataSourceOptions);
    await this.dbConnect.initialize()
  }
like image 120
linusw Avatar answered Jan 20 '26 22:01

linusw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!