jeudi 4 août 2016

Unit testing Angular services in component-based architectures

my current approach is that I have two modules:

  • dashboard, where I keep dashboard component,
  • core where I have alertsWarningsData factory, connecting with backend

My current unit testing approach is explicitly overwriting this service:

dashboard.component.js

angular.
    module('dashboard').
    component('dashboard', {
        controller: DashboardController,
        templateUrl: 'dashboard/dashboard.html'
});

DashboardController.$inject = ['alertsWarningsData'];
function DashboardController(alertsWarningsData) {
    var vm = this;
    setAlertsWarnings();

function setAlertsWarnings() {
    return alertsWarningsData.getAlertsWarnings()
        .then(function(data) {
            vm.alertsWarnings = data;
            return data;
        });
}

dashboard.component.spec.js

describe('Dashboard component', () => {
    let $componentController;
    beforeEach(module('dashboard'));
    beforeEach(inject((_$componentController_) => {
        $componentController = _$componentController_;
    }));

    it(`should exist`, (inject(($q) => {
        // given
        let streamsData = {};
        let alertsWarningsData = {};
        alertsWarningsData.getAlertsWarnings = function() { return $q.defer().promise };

        // when
        const dashboardController = $componentController('dashboard', {'alertsWarningsData': alertsWarningsData});

        // then
        expect(dashboardController).toBeDefined();
    })));
});

Question: Is there any better way to mock this service? So I can do this in beforeEach?

Aucun commentaire:

Enregistrer un commentaire