我的问题与this post非常相似,但差别很大,以至于接受的答案对我不起作用。基本上,我有一个Angular工厂,它使用$ compile,它返回一个promise,我想在Jasmine中嘲笑它。这是工厂的简化版本:
angular.module('app.common')
.factory('myFactory', myFactory);
myFactory.$inject = ['$compile', '$rootScope'];
function myFactory($compile, $rootScope) {
var factory = {
testFunc: testFunc
}
return factory;
function testFunc(stuff) {
angular.element(document.body).append($compile(stuff)($rootScope));
}
}
这是我的测试:
describe("Common", function() {
// I have many common services
beforeEach(function() {
angular.mock.module('app.common');
});
describe("Factory Example: ", function() {
var mockCompile, mockRoot, aFactory;
beforeEach(function() {
module(function($provide) {
$provide.value('$compile', jasmine.createSpy('$compile'));
$provide.value('$rootScope', jasmine.createSpy('$rootScope'));
});
});
beforeEach(inject(function($compile, $rootScope, myFactory, $q) {
mockCompile = $compile;
mockCompile = function() {
var deferred = $q.defer();
deferred.resolve('remote call result');
return deferred.promise;
};
mockRoot = $rootScope;
aFactory = myFactory;
}));
it('should work', function() {
aFactory.testFunc('stuff');
expect(true).toBe(true);
});
});
});
这段代码向我抱怨$ compile不会返回一个promise。似乎$ provide不知道来自inject的新函数赋值。我一直在讨厌它,但我是Jasmine的新手,所以我真的不知道我在做什么。任何帮助将不胜感激 - 如果有更简单的方法来做我想做的事,请告诉我!
答案 0 :(得分:1)
好的,万岁我解决了!
对于那些可能对未来感兴趣的人: 第一个问题是我错误地假设$ compile返回一个promise,但它没有。它返回一个以范围为参数的函数。如果你确实需要模拟一个返回一个promise的函数,请查看this post,这有助于我弄清楚如何。
当然,这对我不起作用,因为我需要做的就是让我的模拟$ compile返回一个函数。以下代码对我有用:
describe("Common", function() {
// I have many common services
beforeEach(function() {
angular.mock.module('app.common');
});
describe("Factory Example: ", function() {
var mockCompile, mockRoot, aFactory;
beforeEach(function() {
module(function($provide) {
// Just use callFake to have $compile return a function
$provide.value('$compile', jasmine.createSpy().and.callFake(function() {
return function(scope) { scope(); };
});
$provide.value('$rootScope', jasmine.createSpy());
});
});
beforeEach(inject(function($compile, $rootScope, myFactory, $q) {
mockCompile = $compile;
mockRoot = $rootScope;
aFactory = myFactory;
}));
it('should work', function() {
aFactory.testFunc('stuff');
expect(mockCompile).toHaveBeenCalled();
expect(mockRoot).toHaveBeenCalled();
});
});