pQuestions123
pQuestions123

Reputation: 4611

Aurelia Unit Test - How to mock a custom resolver

Here is the class that I am trying to test:

import {inject} from 'aurelia-framework';
import {CrudResource, DependencyFactory} from 'utils';

let commonData = {};
    @inject(DependencyFactory.of(CrudResource))
    export class CommonDataCache {
        constructor(crudResourceFactory) {
            this.crudResource = crudResourceFactory('/Common');
        }
        data() {
            return Object.keys(commonData).length > 0 ? commonData :
                this.crudResource.get().then(response => {
                    commonData.clientEntities = response;
                    return commonData;
                });
        }
    }

I am attempting to write this test (posted only the relevant part for brevity):

beforeEach(() => {
        container = new Container();

        container.registerInstance('DependencyFactory.of(CrudResource)', new CrudResourceFactoryMock());

        templatingEngine = container.get(TemplatingEngine);

        cdc = templatingEngine.createViewModelForUnitTest(CommonDataCache);
    });

Basically, since my class is injecting a factory of the resource (the factory just allows me to configure the injected dependency on construction), I am attempting to pass in a mocked factory (which will pass in a mocked dependency).

The issue that I am facing is that somehow the CommonDataCache class is being instantiated with its regular dependency (as opposed to my mocked one). Somehow aurelia doesn't understand that I have registered a mocked factory for the 'DependencyFactory.of(CrudResource)' resolution.

Thanks in advance.

Upvotes: 0

Views: 707

Answers (1)

Ashley Grant
Ashley Grant

Reputation: 10897

I personally wouldn't use Dependency injection in a Unit Test. I would create a mock and pass that to the constructor for CommonDataCache.

Once you start using the DI system, you're no longer creating Unit Tests, but are starting to create E2E tests.

Upvotes: 1

Related Questions