我正在尝试为学习目的测试一项简单的服务。但是;我无法弄清楚它是如何完成的:
服务:
.factory('myService', function($http) {
var myService = {
async: function() {
var promise = $http.get('test.json').then(function (response)
{
return response.data;
});
return promise;
}
};
return myService;
});
控制器:
myService.async().then(function(d) {
$scope.data = d;
$scope.e = $scope.data.txt;
});
试验:
'use strict';
describe("myService", function(){
beforeEach(module("testingExpApp"));
var myService,
$httpBackend;
beforeEach(inject(function(myService, _$httpBackend_){
myService = myService;
$httpBackend = _$httpBackend_;
}));
describe("get", function(){
it('should return test.json data', function () {
var url = "../mock/test.json";
var x = $httpBackend.expectGET(url).respond(200, 'txt from json');
// flush response
$httpBackend.flush();
expect(x).toBe('txt from json');
});
});
});
我没有等待刷新的待处理请求!'
我只是想测试myservice.get()获取test.json文件数据..我已经尝试了所有东西,但无法让它工作..
任何提示?
提前多多感谢!
答案 0 :(得分:0)
我缺少的是致电服务功能
必须是:
it('should return test.json data', function () {
var url = "../../mock/test.json";
$httpBackend.expectGET(url).respond(200, 'data from test.json');
//Execute service func here..
myServiceFunc.async().then(function(result) {
console.log(result);
expect(result).toEqual('data from test.json');
});
$httpBackend.flush();
});