1

我有以下测试代码:

describe('imagesCtrl', function () {
    var $rootScope;
    var $compile;
    var $log;
    var $controller;
    var imagesCtrl;
    var $q;
    var images;
    var vm;

beforeEach(module('flickrPOC'));

beforeEach(module(function ($provide) {

    $provide.service('images', function () {
        this.loadPics = sinon.stub().returns($q.resolve({message: 'object data from stub'}));
    });

}));

beforeEach(inject(function (_$rootScope_, _$compile_, _$log_, _$controller_, _$q_, _images_) {
    $compile = _$compile_;
    $rootScope = _$rootScope_;
    $log = _$log_;
    $controller = _$controller_;
    $q = _$q_;
    images = _images_;

    vm = $controller('imagesCtrl');

}));

describe('imagesCtrl', function () {
    beforeEach(function () {
        images.loadPics.returns($q.resolve({message: 'd'}));
    });

    it('should exist', function () {
        expect(vm.getImages).to.exist();
    }
});
});

我正在注入一个控制器,其设置如下:

(function (angular) {
angular
    .module('flickrPOC')
    .controller('imagesCtrl', imagesCtrl);

imagesCtrl.$inject = ['images', '$compile', '$http', '$q'];

function imagesCtrl(images, $compile, $http, $q) {
    /* jshint validthis: true */
    var vm = this;

    vm.getImages = function () {
        images.loadPics()
            .then(function (res) {
                console.log(res);
                vm.images = res.name;
            })
            .catch(
                function(err){
                    console.error('Error loading images ', err.status, err.data);
                })
            .finally(function () {
                console.log("finally finished");
            });
    };
}

})(angular);

运行测试时,我收到以下错误:

PhantomJS 1.9.8 (Mac OS X 0.0.0) imagesCtrl "before each" hook: workFn for "should exist" FAILED TypeError: 'undefined' is not an object (evalating '$q.resolve') at..src/js /controllers/imageCtrl-test.js:18;

这个错误是指 this.loadPics = sinon.stub().returns($q.resolve({.....}));

4

1 回答 1

0

所以答案是依赖注入。起初我试图在每个之前注入 $q:

beforeEach(module(function ($provide, $q) {

    $provide.service('images', function () {
        this.loadPics = sinon.stub().returns($q.resolve({message: 'object data from service stub'}));
    });

}));

正确的方法是将其注入 $provider,如下所示:

beforeEach(module(function ($provide) {

    $provide.service('images', function ($q) {
        this.loadPics = sinon.stub().returns($q.resolve({message: 'object data from service stub'}));
    });

}));

在此之后,一切正常。

于 2016-01-06T16:27:54.800 回答