【发布时间】:2015-04-09 13:28:36
【问题描述】:
到目前为止,我一直一无所知。假设我有这个非常简单的应用模块:
var app = angular.module('myApp', []);
app.service('searchService', ['$http', function($http){
var baseURL="https://someonehost.com/product/search&query=";
return {
search: function(query){
return $http.get(baseURL+query);
}
};
}]);
app.controller('mainCtrl', ['$scope','searchService',function($scope, searchService) {
searchService.search($scope.searchWords).success(function(data) {
$scope.responseData=data;
});
}]);
它适用于浏览器。现在我尝试使用 karma、mocha 和 chai 对其进行测试。假设我想写一个测试用例来测试请求的成功路径。我该怎么写?这是我目前正在尝试的:
describe('',function(){
var $httpBackend = null;
var locationService = null;
var baseURL="https://someonehost.com/product/search&query=";
beforeEach(function(){
module('myApp');
inject(function(_$httpBackend_,_locationService_){
$httpBackend = _$httpBackend_;
locationService = _locationService_;
});
});
it('test case 1',function(){
var searchWord = 'car';
$httpBackend.when('GET',baseURL+searchWord).respond(200,'');
$httpBackend.expectGET(baseURL+searchWord);
searchService.search(searchWord).success(function(data) {
console.log('data: '+data);
});
$httpBackend.flush();
});
});
但它没有返回任何数据,它应该在控制台中返回:
LOG: 'data: '
Firefox 37.0.0 (Ubuntu): Executed 1 of 1 SUCCESS (0.033 secs / 0.006 secs)
【问题讨论】:
-
该错误表明呼叫应该是 'car' 而不是 'myhost.com/product/search ... &query=car' 这就是正在发生的事情。我认为问题出在你的测试上。
-
是的,我知道,但我不知道如何为这个案例编写一个合适的测试用例,因为我没有这方面的经验/知识
标签: angularjs unit-testing karma-runner mocha.js chai