我尝试在茉莉花测试中向我的控制器注入一个工厂 Unit testing AngularJS factories that have dependencies
当我在测试中提供工厂时,我希望控制器使用提供的工厂。但是console.log仍然打印出真正的价值'。我不明白。
var app = angular.module('mod', []);
app.factory('factoryA', [
function () {
return "real value";
}
]);
app.controller('myController', ['factoryA',
function (factoryA) {
console.log(factoryA);
}
]);
describe("test", function() {
var $scope, $controller, $httpBackend;
var app;
beforeEach(function() {
module(function($provide) {
$provide.factory('factoryA', function () { return "fake value"; });
});
app = module("mod");
inject(function (_$controller_, _$httpBackend_, $rootScope) {
$httpBackend = _$httpBackend_;
$scope = $rootScope.$new();
$controller = _$controller_;
});
});
it("works", function() {
$controller("myController", { '$scope': $scope });
});
});
答案 0 :(得分:4)
您需要从模块$provide
获取mod
r,因此将模块名称作为第一个参数传递,以便它覆盖最初创建的factoryA
定义。或者在设置模拟之前加载模块 - module("mod")
。
module('mod', function($provide) {
$provide.factory('factoryA', function () { return "fake value"; });
});
创建模拟并将其传递给控制器创建的另一种方法。
describe("test", function() {
var $scope, $controller, $httpBackend;
var app, factoryA;
beforeEach(function() {
module(mod);
inject(function (_$controller_, _$httpBackend_, $rootScope) {
//...Your code
//Mock factory
factoryA = jasmine.createSpy('factoryA');
factoryA.and.returnValue("fake value");
});
});
it("works", function() {
//Pass the mock factory
$controller("myController", { '$scope': $scope, factoryA:factoryA });
});
});