import ( "reflect-metadata" ) ; import { assert } from "chai" ; import { reset , override , autowired , reflection } from "../src/index" ; describe ( "DI.ts" , ( ) => { describe ( "resolve dependencies" , ( ) => { afterEach ( ( ) => { reset ( ) ; } ) ; it ( "sample in easy mode" , async ( ) => { @ reflection class ProdRepository { public async getData ( ) { return Promise . resolve ( "production" ) ; } } @ reflection class MockRepository implements ProdRepository { public async getData ( ) { return Promise . resolve ( "mock" ) ; } } @ reflection class ProdService { public constructor ( private readonly prodRepository ) { } public async getData ( ) { return this . prodRepository . getData ( ) ; } } class ProdController { @ autowired ( ) private readonly prodService ! : ProdService ; public async getData ( ) { return this . prodService . getData ( ) ; } } if ( process . env . NODE_ENV === "test" ) { override ( ProdRepository , MockRepository ) ; } const controllerInstance = new ProdController ( ) ; const data = await controllerInstance . getData ( ) ; if ( process . env . NODE_ENV === "test" ) { assert . strictEqual ( data , "mock" ) ; } else { assert . strictEqual ( data , "production" ) ; } } ) ; it ( "sample in pro mode" , async ( ) => { abstract class AbstractRepository { public abstract getData ( ) ; } @ reflection class ProdRepository implements AbstractRepository { public async getData ( ) { return Promise . resolve ( "production" ) ; } } @ reflection class MockRepository implements AbstractRepository { public async getData ( ) { return Promise . resolve ( "mock" ) ; } } abstract class AbstractService { public abstract getData ( ) ; } @ reflection class ProdService implements AbstractService { private readonly prodRepository : AbstractRepository ; public constructor ( prodRepository ) { this . prodRepository = prodRepository ; } public async getData ( ) { return this . prodRepository . getData ( ) ; } } class ProdController { @ autowired ( ) private readonly prodService ! : AbstractService ; public async getData ( ) { return this . prodService . getData ( ) ; } } override ( AbstractService , ProdService ) ; if ( process . env . NODE_ENV === "test" ) { override ( AbstractRepository , MockRepository ) ; } else { override ( AbstractRepository , ProdRepository ) ; } const controllerInstance = new ProdController ( ) ; const data = await controllerInstance . getData ( ) ; if ( process . env . NODE_ENV === "test" ) { assert . strictEqual ( data , "mock" ) ; } else { assert . strictEqual ( data , "production" ) ; } } ) ; } ) ; } ) ;