我将开始说$ httpBackend和spyOn对我来说是一个新手,我正在努力清楚地了解正在发生的事情。基本上,我试图做一个 $ httpBackend.expectGET(&#39; / myroute /&#39;)。回应(...)然后使用 spyOn < / em>,但我一直在
h2 {
/* font-family: 'Fjalla One', sans-serif; */
font-family: 'PNS', sans-serif;
}
这是我试图测试的代码:
Expected [ ] to equal Object({ success: true, message: 'Yeah!' })
这是我的Karma-Jasmine测试:
angular.module('TestModule')
.service('TestService',TestService);
TestService.$inject = ['$http'];
function TestService($http){
var service = {};
service.DoIt = DoIt;
return service;
function DoIt() {
return $http.get('/myroute/')
.then(handleSuccess,handleError('Error happened!'));
}
function handleSuccess(res) {
return res.data;
}
function handleError(error) {
return function(){
return {success: false, message: error}
};
}
}
更多信息:
使用我在此处找到的示例:http://www.bradoncode.com/blog/2015/06/26/unit-testing-http-ngmock-fundamentals/,我在测试代码中尝试了这个:
describe('Test Module',function(){
beforeEach(module('TestModule'));
describe('TestService Tests',function(){
var service,$httpBackend;
beforeEach(inject([
'$injector',
function($injector){
$httpBackend = $injector.get('$httpBackend');
service = $injector.get('TestService');
}
]));
afterEach(function(){
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should DoIt',function(){
var mockResponse = {
data : {success:true, message:"Yeah!"}
};
$httpBackend.expectGET('/myroute')
.respond(Promise.resolve(mockResponse));
spyOn(service,'DoIt').and.callThrough();
service.DoIt().then(function(data){
expect(service.DoIt).toHaveBeenCalled();
expect(data).toEqual(mockResponse.data); <-- ERROR OCCURS HERE -->
});
$httpBackend.flush();
});
});
});
这给了我期待的响应:&#39;数据:{&#34;数据&#34;:&#34;是的&#34;}&#39;
我的更新问题:我认为service.DoIt()与承诺做同样的事情。这里发生了什么?我不是在注射我的服务吗?我不明白Karma希望我如何进行这项测试。请帮忙!
答案 0 :(得分:2)
如果我理解你的测试意图,我相信这就是你需要的:
describe('Test Module', function() {
var $httpBackend, service;
beforeEach(module('TestService'));
beforeEach(inject(function(_$httpBackend_, _TestService_) {
$httpBackend = _$httpBackend_;
service = _TestService_;
}));
afterEach(function() {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should DoIt', function() {
var mockResponse = {
data: { success: true, message: "Yeah!" }
};
$httpBackend.expectGET('/myroute/')
.respond(mockResponse);
service.DoIt().then(function(data) {
expect(data).toEqual(mockResponse);
});
$httpBackend.flush();
});
});
答案 1 :(得分:0)
就我而言,transformResponse
上的$resource
函数修改了预期的模拟数据:
var resource = $resource('api/data/:id', {}, {
get: {
method: 'GET',
isArray: true,
transformResponse: function (data) {
var d = angular.fromJson(data);
return d.members;
}
}
...
我的模拟数据不包含成员...