0

Looking for typescript sample code for creating knex database instance through dependency injection. Goal is to mock knex in unit testing and not hardwiring knex instance in the DAO files for data acccess

Rajeev
  • 1
  • 1

1 Answers1

0

You might want to use a dependency injection framework such as Dime. It's a very simple framework for dependency injection.

Setup:

In terminal:

npm install @coined/dime

In tsconfig.json:

{
  "compilerOptions": {
    "lib": ["es2019", "es2020.promise", "es2020.bigint", "es2020.string"],
    "module": "commonjs",
    "target": "es2019",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true,
    "forceConsistentCasingInFileNames": true,
    "moduleResolution": "node",
    "experimentalDecorators": true,
    "strictPropertyInitialization": false
  }
}

In your source Typescript file:

const dbInstance = db.getConnection(); // or whatever you use to create an instance

const appPackage = new Package("App", {
  token: "dbInstance",
  provideValue: dbInstance
});

Dime.mountPackages(appPackage);

To use the db instance:

Dime.injector.get("dbInstance").executeQuery("...");

Now, if you wanted to test this, you could replace dbInstance with a mock.

anut
  • 481
  • 1
  • 11