【发布时间】:2014-11-21 09:00:57
【问题描述】:
我正在尝试编写一个单元测试来测试一个简单的 factory,它执行 http.get 来检索 JSON 文件。
工厂在我的控制器中被调用。
这是一个显示我的 http.get 的 plunker:http://plnkr.co/edit/xg9T5H1Kreo4lwxzRQem?p=preview
Ctrl:
app.controller('MainCtrl', function($scope, $http, factoryGetJSONFile) {
factoryGetJSONFile.getMyData(function(data) {
$scope.Addresses = data.Addresses.AddressList;
$scope.People = data.Names.People;
});
});
工厂:
app.factory('factoryGetJSONFile', function($http) {
return {
getMyData: function(done) {
$http.get('data.json')
.success(function(data) {
done(data);
})
.error(function(error) {
alert('An error occured whilst trying to retrieve your data');
});
}
}
});
测试:
// ---SPECS-------------------------
describe('with httpBackend', function () {
var app;
beforeEach(function () {
app = angular.mock.module('plunker')
});
describe('MyCtrl', function () {
var scope, ctrl, theService, httpMock;
beforeEach(inject(function ($controller, $rootScope, factoryGetJSONFile, $httpBackend) {
scope = $rootScope.$new(),
ctrl = $controller('MyCtrl', {
$scope: scope,
factoryGetJSONFile: theService,
$httpBackend: httpMock
});
}));
it("should make a GET call to data.json", function () {
console.log("********** SERVICE ***********");
httpMock.expectGET("data.json").respond("Response found!");
//expect(factoryGetJSONFile.getMyData()).toBeDefined();
httpMock.flush();
});
})
});
错误:
TypeError: 'undefined' is not an object (evaluating 'httpMock.expectGET')
【问题讨论】:
-
你在哪里定义 theService 对象?
-
您的代码现在只有在您编写 factoryGetJSONFile: factoryGetJSONFile 时才会编译,但它只会调用原始服务。您必须定义一个模拟服务并将其放入服务中
标签: angularjs unit-testing angularjs-scope jasmine karma-jasmine