我正在努力为RESTful资源编写一些测试。我是框架的新手,所以请相应地调整您的解释。
我正在使用角度模拟+ Karma-Jasmine进行单元测试。这是REST资源测试对象:
angular.module('resources', ['ngResource'])
.factory('Login', function($resource, helpers) {
return $resource(
helpers.getApiUrl() + 'login'
);
})
helpers是另一个模块中定义的常量:
app = angular.module('app', ['ngRoute', 'filters', 'services', 'resources']).constant('helpers', {
getLanguage : function() { return angular.element('meta[http-equiv]').attr('content'); },
getApiUrl : function() { return '<%= @site.config[:api] %>'.replace(/\%\{lang\}/,this.getLanguage() + '.'); }
}).config(['$routeProvider', '$anchorScrollProvider', 'helpers', config]).run(runner)
最后,这是有问题的单元测试:
describe("Resources test suite", function() {
var mockHelpers;
beforeEach(function(){
mockHelpers = sinon.stub({ getLanguage: function() {return 'de';}, getApiUrl: function(){ return 'http://testApiUrl/';} });
module('app', function($provide) {
$provide.constant('helpers', mockHelpers);
})
});
beforeEach(module('resources'));
describe('Login resource', function() {
it('should send a post resquest to /login', inject(function(Login, $httpBackend, helpers){
var url = 'http://testApiUrl/login',
data = 'mock data',
headers = {"Accept": "application/json, text/plain, */*", "Content-Type":"application/json;charset=utf-8"},
successCallback = jasmine.createSpy('success'),
errorCallback = jasmine.createSpy('error');
$httpBackend.expectPOST(url, data, headers).respond(200, {token:'Oh yeah!'});
var answer = Login.save(data);
$httpBackend.flush();
expect(answer.token).toBe('Oh yeah!');
expect(errorCallback).not.toHaveBeenCalled();
}))
})
});
测试失败了,我不明白为什么。似乎没有定义模拟getApiUrl函数(这里是来自karma的控制台输出):
Chrome 34.0.1847 (Linux) Resources test suite Login resource should send a post resquest to /login FAILED
Error: Unexpected request: POST undefinedlogin
Expected POST http://testApiUrl/login
我被困在这里。有人知道可能出了什么问题吗?我会感激任何帮助。
答案 0 :(得分:0)
beforeEach(
function () {
mockHelpers = { getApiUrl: function(){ return 'testApiUrl/';} };
module('app',function($provide) {$provide.constant('helpers', mockHelpers);});
}
);