lundi 28 mars 2016

Aurelia unit test gone wrong (Karma/Jasmine)

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;
            });
    }
}

as you can see this is a kind of client-side data cache which depends on a crud-resource. All of this works fine (i.e. it is bringing the data that I expect down when I run the app).

Now here is the test I am attempting to write:

import {CommonDataCache} from 'utils';
import {Container, TemplatingEngine} from 'aurelia-framework';
import {CrudResource} from 'utils';

describe('CommonDataCache class', () => {
    let cdc;
    let container;
    let templatingEngine;

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

        templatingEngine = container.get(TemplatingEngine);
        container.registerSingleton(CrudResource, MockCrudResource);

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

    describe('caching mechanism', () => {
        it('gets from crud resource on initial call', (done) => {
            cdc.data()
                .then(data => {
                    expect(data.clientEntities.length).toEqual(2);
                    done();
                });
        });
        it('returns initial data even if remote data is changed', (done) => {
            cdc.crudResource.data.clientEntities.push({});
            cdc.data()
                .then(data => {
                    expect(data.clientEntities.length).toEqual(2);
                    done();
                });
        });
    });
});

class MockCrudResource {
    constructor() {
        this.data = {
            clientEntities: [
                {}, {}
            ]
        };
    }
    get() {
        return Promise.resolve(this.data);
    }
}

What I am trying to do: mock the async crud resource and then add it to the container so that when the CommonDataCache gets instantiated it will use the mocked up crud resource.

When I try to run this test though I get thrown all kinds of errors and the test fails. I guess I am probably using one or more methods incorrectly or making some incorrect assumption.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire