【发布时间】:2015-12-03 21:58:23
【问题描述】:
我对单元测试很陌生。我正在编写代码。我的 js 文件有:
app.service("appService", function($http) {
this.getData = function(url) {
return $http.get(url);
}
this.foo = function() {
console.log("Hello foo function");
}
})
app.controller("productsController", ['$scope', '$http', 'appService',
function($scope, $http, appService) {
var pct = this;
console.log("This is products controller");
pct.url = "http://mysafeinfo.com/api/data?list=englishmonarchs&format=json";
var jsonDataPromise = appService.getData(pct.url);
jsonDataPromise
.then(function(response) {
pct.jsonData = response.data;
}, function(err) {
console.log("Error is: " + error);
});
}
]);
我正在使用 jasmine 框架在 karma.js 中对其进行单元测试。我已将 testfile.js 设为:
describe('unitTesting', function() {
var $prodScope, prodCtrl, mockService;
beforeEach(module('sampleApp')); //Name of angular module
var jsonData = {
"name": "test_name",
"email": "test_email"
};
beforeEach(function() {
mockService = jasmine.createSpyObj('appService', ['getData', 'foo']);
})
beforeEach(inject(function($controller, $rootScope, $httpBackend, $http, $q, mockService) {
defer = $q.defer();
$prodScope = $rootScope.$new();
prodCtrl = $controller('productsController', {
$scope: $prodScope,
$http: $http,
appService: mockService
});
spyOn(mockService, "getData").and.callFake(function() {
return defer.promise;
});
spyOn(mockService, "foo");
}));
//Here unit tests go
})
我的问题是,当我使用 karma start 运行测试时(我有 karma.conf.js),我收到错误:
[$injector:unpr]未知提供者:mockServiceProvider
谁能向我解释为什么我会收到这个错误?请解释正确的代码应该是什么。
【问题讨论】:
标签: javascript angularjs node.js unit-testing