在Angular中制作sinon存根时,获取undefined不是对象错误

时间:2016-01-06 15:36:05

标签: angularjs sinon stub karma-mocha sinon-chai

我有以下测试代码:

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“每个”之前的钩子:workFn for“应该存在”FAILED         TypeError:'undefined'不是对象(评估'$ q.resolve')             at..src / JS /控制器/ imageCtrl-test.js:18;

此错误指的是该行     this.loadPics = sinon.stub()。return($ q.resolve({.....}));

1 个答案:

答案 0 :(得分: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'}));
    });

}));

在此之后,一切正常。