jeudi 29 octobre 2015

Unit Testing Ember Services that Fetch Data

I have an ember service thats primary concern is to fetch data for a specific model and the descendants of the model. The reason I am using this in a service is because the route for this particular type is using a slug which is not the primary key and therefore needs to do a store.query instead of store.find. When we fetch this model I have some logic that peeks the ember store to see if we can load it from there before going to the api query. Also this vendor is watching for the slug change and updating the current model based on that.

The problem I am having is that this seems to have very little documentation when it comes to how to test a thing like this. In fact I don't see a section on testing services anywhere in the guides here http://ift.tt/20d8nr7

This is a snippet of the service in question.

import Ember from 'ember';

export default Ember.Service.extend({
    _vendorSlug: null,
    vendor: null,

    vendorSlug: function (key, value) {
        if (arguments.length > 1) {
            if (this._vendorSlug) {
                return this._vendorSlug;
            }

            this._vendorSlug = value;
        }

        return this._vendorSlug;
    }.property(),

    ensureVendorLoaded: function (slug) {
        var service = this,
            vendorSlug = slug || service.get('vendorSlug'),
            currentVendor = service.get('vendor'),
            storedVendor;

        if (!Ember.isNone(currentVendor) && (vendorSlug === currentVendor.get('slug'))) {
            return new Ember.RSVP.Promise((resolve) => {
                        resolve(currentVendor);
                    });
        } else {
            var storedVendors = service.store.peekAll('vendor').filter((vendor) => { 
                return vendor.get('slug') === vendorSlug;
            });

            if (storedVendors.length) {
                storedVendor = storedVendors[0];
            }
        }

        if (!Ember.isNone(storedVendor)) {
            service.set('vendorSlug', storedVendor.get('slug'));

            return new Ember.RSVP.Promise((resolve) => {
                    resolve(storedVendor);
                });
        }

        return service.store.queryRecord('vendor', {slug: vendorSlug}).then((vendor) => {
            service.set('vendor', vendor);
            service.set('vendorSlug', vendor.get('slug'));

            return vendor;
        });
    },

    _vendorSlugChanged: function () {
        if (this.get("vendorSlug") === this.get("vendor.slug")) {
            return;
        }

        this.ensureVendorLoaded();
    }.observes('vendorSlug')
});

Aucun commentaire:

Enregistrer un commentaire