vendredi 20 novembre 2015

AngularJS, Jasmin and $ressource = promise not resolved

i have problems to build a jasmin test on top of a mocked ressource factory.

The (working) Szenario

Controller:

.controller("remoteCtrl", function(resourceFactory) {
  var vm = this;

  vm.animals = resourceFactory.getAll();
});

Factory

        .factory('resourceFactory', function ($resource) {
            var demoResource = $resource('/demo-1.0/webresources/animal/:id', {id: '@id'}, {
                getAll: {method: 'GET', isArray: true},
                getFirst: {method: 'GET', params: {id: 0}, isArray: false},
                save: {method: 'POST', params: {id: null}}
            });

            return demoResource;
        });

MockModule for Backendless Development:

angular.module('playAngular.mock', ['ngMockE2E'])

        .run(function ($httpBackend, $log) {

            var animals = [
                {name: 'Animal1', age: '100', id: 0},
                {name: 'Animal2', age: '100', id: 1},
                {name: 'Animal3', age: '100', id: 2},
                {name: 'Animal4', age: '100', id: 3}
            ];

            $httpBackend.whenGET('/demo-1.0/webresources/animal').respond(function () {
                return [200, animals];
            });
  //....

That is working fine all together. But now the problematic point. I want to test my Controller with Jasmin:

describe("Test Suite für RemoteController", function () {
    beforeEach(module('ngResource'));
    beforeEach(module('ngMockE2E'));
    beforeEach(module('playAngular.mock'));
    beforeEach(module('playAngular.remote'));
    
    var $controller;
    var $scope;
    var $rootScope;

    beforeEach(inject(function (_$controller_, _$rootScope_) {
        $controller = _$controller_;
        $rootScope = _$rootScope_;
    }));

    var controller;
    beforeEach(function () {
        controller = $controller('remoteCtrl', {$scope: $scope});

    });

    describe("Basic Remote Test", function () {
        it('Test It:', function () {
            expect(controller).toBeDefined();
            expect(controller.animals).toBe(4);
        });
    });
});

The test will fail:

Expected [ $promise: Promise({ $$state: Object({ status: 0 }) }), $resolved: false ] to be 4.

I understand the error, we have an unresolved promise here, but how can i get it working to wait and test the repond in jasmin test? This one:

controller.animals.$promise.then(function(result){ expect(result.length).toBe(4); });

won't work as well (jasmin dont't wait for the resonse and just return with "all fine".

I try all hints i found in web:trigger digest cycle, flush httpbackend, but nothign worked... somebody see the problem?

Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire