Search code examples
unit-testingtypescriptdependency-injectioninversifyjs

constructor injection using inversifyJS and Alsatian test framework


Hoping someone can guide me in the right direction here I'm using inversifyJS with Alsatian testing framework

basically the design calls for utilising several services, including database and other api clients, I thought it'd be a good idea to get IOC in place to manage the dependencies

the problem I'm facing with Alsatian framework is that neither the property injection or the constructor injection works, only manually resolving it form the container works

    private resolvedNinja: Warrior;
    // does not inject property
    @inject(ServiceTypes.Warrior) private propertyNinja: Warrior;


    public constructor(
        // does not inject
        @inject(ServiceTypes.Warrior) constructorNinja:Warrior
    ){
        console.log("constructor called");

        // this injects and works
        this.resolvedNinja = container.get<Warrior>(ServiceTypes.Warrior);

        console.log("injected constructor ninja " + constructorNinja);
        console.log("injected property ninja " + this.propertyNinja);
        console.log("resolved ninja " + this.resolvedNinja);

    }

I'm not sure why, I've cleaned and setup a small test project if anyone is interested in checking it out

https://github.com/dshamim/alsatian-test-ioc

you need to have yarn to run to run, goto the project directory and type:

yarn install

yarn run ts-node Tests/runner.ts --tap

I'm trying to keep the code structured, so if anyone has any ideas what can be done to get the constructor injection working, that would be great


Solution

  • The sad answer is "You can't". Alsatian uses the new operator to instanciate the classes of your test Fixtures. So, inverisfy has no way of knowing that must inject dependencies into the Fixture class. (Remember that dependencies are injected when the class is instantiated with container.get())