mardi 22 décembre 2015

Testing AngularJS controllers with resource

I am trying to begin writing unit tests for my angular application. Here is small part from my controller

    $scope.getBrands = function () {
        var deferred = $q.defer();
        Brands.get({
            limit: 1000
        }, function (data) {
            $scope.carBrands = data.items;
            deferred.resolve();
        });
        return deferred.promise;
    };

    $scope.getBrands().then(function () {
        $scope.tableParams = new ngTableParams({
            page: 1,
            count: 10
        }, {
            total: $scope.carBrands.length,
............................................................................

My factory

angular.module('app.core').factory("Brands", ['$resource', 'appCoreConfig', function($resource, appCoreConfig) {
  return $resource(appCoreConfig.baseServer + "/v1/api/rest/brand/:id", {},{
    get: {
        method: 'GET',
        cache: false
    }
  });
}]);

And test

describe('Brands', function () {
    //Testing controller BrandsController...
    describe('BrandsController', function () {
        var $scope, $httpBackend, appCoreConfig;

        beforeEach(module('app.brands', function ($translateProvider) {
            $translateProvider.translations('en', {});
        }));

        beforeEach(inject(function ($rootScope, $controller, $injector) {
            $httpBackend = $injector.get('$httpBackend');
            $scope = $rootScope.$new();

            appCoreConfig = $injector.get('appCoreConfig');

            $controller('BrandsController', {$scope: $scope});
        }));

        //--------------------Our tests-------------------------------------
        it('Test', function () {
            var url = appCoreConfig.baseServer + '/v1/api/rest/brand?limit=1000';
            $httpBackend.whenGET(url).respond(200, {});
            $httpBackend.flush();
        })
    });
});

I want to check that
1) This request works correctly (and return correct data)
2) Value of $scope.carBrands

Now, I get

TypeError: 'undefined' is not an object (evaluating '$scope.carBrands.length')

Data, that will be in $scope.carBrands:

[{code: "ACURA", enabled: false, id: 33, name: "ACURA",oem: true}]

How can I resolve my problem?

Aucun commentaire:

Enregistrer un commentaire