我正在尝试使用Angular $资源对REST请求进行一些基本测试。 服务代码工作得很好。
'use strict';
angular.module('lelylan.services', ['ngResource']).
factory('Device', ['Settings', '$resource', '$http', function(Settings, $resource, $http) {
var token = 'df39d56eaa83cf94ef546cebdfb31241327e62f8712ddc4fad0297e8de746f62';
$http.defaults.headers.common["Authorization"] = 'Bearer ' + token;
var resource = $resource(
'http://localhost:port/devices/:id',
{ port: ':3001', id: '@id' },
{ update: { method: 'PUT' } }
);
return resource;
}]);
我在指令中使用Device资源并且它可以工作。问题出来了 当我开始对服务进行一些测试时。这是一个示例测试,我嘲笑 使用$ httpBackend的HTTP请求,我向模拟的URL发出请求。
不幸的是,虽然提出了请求,但它不会返回任何内容。我很确定这一点 因为如果对另一个URL发出请求,测试套件会自动引发错误。 我花了很多时间,但没有解决方案。这是测试代码。
'use strict';
var $httpBackend;
describe('Services', function() {
beforeEach(module('lelylan'));
beforeEach(inject(function($injector) {
var uri = 'http://localhost:3001/devices/50c61ff1d033a9b610000001';
var device = { name: 'Light', updated_at: '2012-12-20T18:40:19Z' };
$httpBackend = $injector.get('$httpBackend');
$httpBackend.whenGET(uri).respond(device)
}));
describe('Device#get', function() {
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' });
expect(device.name).toEqual('Light');
}));
});
});
由于设备未加载,这是错误。
Expected undefined to equal 'Light'.
Error: Expected undefined to equal 'Light'.
我也试过使用以下解决方案,但它没有进入该功能 检查期望。
it('returns a JSON', inject(function(Device) {
device = Device.get({ id: '50c61ff1d033a9b610000001' }, function() {
expect(device.name).toEqual('Light');
});
}));
非常感谢任何解决此问题的建议或链接。 非常感谢。
答案 0 :(得分:5)
你非常接近,唯一缺少的就是打电话给$httpBackend.flush();
。工作测试如下:
it('returns a JSON', inject(function(Device) {
var device = Device.get({ id: '50c61ff1d033a9b610000001' });
$httpBackend.flush();
expect(device.name).toEqual('Light');
}));
在plunker中进行实时测试:http://plnkr.co/edit/Pp0LbLHs0Qxlgqkl948l?p=preview
您可能还想查看docs for the $httpBackend mock。
答案 1 :(得分:0)
在更高版本的angular中,我使用的是1.2.0rc1,你还需要在一个$ apply中调用它,或者在一个范围内调用$ digest。除非您执行以下操作,否则不会进行资源调用:
var o, back, scope;
beforeEach(inject(function( $httpBackend, TestAPI,$rootScope) {
o = TestAPI;
back = $httpBackend;
scope = $rootScope.$new();
}));
it('should call the test api service', function() {
back.whenGET('/api/test').respond({});
back.expectGET('/api/test');
scope.$apply( o.test());
back.flush();
});