如何让这个单元测试工作?
控制器:
var app = angular.module('plunker', []);
app.controller('myCtrl', function ($http, $scope) {
$http.get('https://api.github.com/users/jasonmore').then(function (data) {
$scope.myData = data;
},
function (err) {
console.log(err);
}
);
})
和规范:
describe('mocking service http call', function () {
beforeEach(module('plunker'));
var myCtrl, $scope;
describe('with httpBackend', function () {
beforeEach(inject(function ($controller, $rootScope, $httpBackend) {
$scope = $rootScope.$new();
$httpBackend.when('GET', 'https://api.github.com/users/jasonmore')
.respond({data:{}});
myCtrl = $controller('myCtrl', { $scope: $scope });
$httpBackend.flush();
}));
it('should set data ', function () {
expect($scope.myData).toEqual({data:{}});
});
});
});
如何修复此错误信息:
Expected { data : { data : { } }, status : 200, headers : Function, config : { method : 'GET', transformRequest : [ Function ], transformResponse : [ Function ], url : 'https://api.github.com/users/jasonmore', headers : { Accept : 'application/json, text/plain, */*' } }, statusText : '' } to equal { data : { } }.
答案 0 :(得分:0)
当您使用$http.then
而不是success
时,响应包含一个具有属性的对象
数据,状态,标题,配置
因此回调分配不正确。它应该是:
$http.get('https://api.github.com/users/jasonmore').then(function (data) {
$scope.myData = data.data; //this needs to be data.data
},
function (err) {
console.log(err);
}
);