我正在尝试通过Karma对使用Jasmine构建的Angular上的应用进行单元测试。该应用程序涉及调用GitHub API并提取用户的所有存储库的名称并使用这些名称填充数组。我正在尝试测试阵列是否已经填满,但我遇到了一些问题,而且我们遇到了一些问题。
我的控制器的相关部分是:
readmeSearch.controller('ReadMeSearchController', ['RepoSearch', function(RepoSearch) {
var self = this;
self.gitRepoNames = [];
self.doSearch = function() {
var namesPromise =
RepoSearch.query(self.username)
.then(function(repoResponse) {
addRepoNames(repoResponse);
}).catch(function(error) {
console.log('error: ' + error);
});
return namesPromise;
};
addRepoNames = function(response) {
self.repoSearchResult = response.data;
for(var i = 0; i < self.repoSearchResult.length; i++) {
var name = self.repoSearchResult[i]['name']
self.gitRepoNames.push(name);
};
};
}]);
我的RepoSearch工厂是:
readmeSearch.factory('RepoSearch', ['$http', function($http) {
return {
query: function(searchTerm) {
return $http({
url: 'https://api.github.com/users/' + searchTerm + '/repos',
method: 'GET',
params: {
'access_token': gitAccessToken
}
});
}
};
}]);
有问题的测试是这样的:
describe('ReadMeSearchController', function() {
beforeEach(module('ReadMeter'));
var ctrl;
beforeEach(inject(function($controller) {
ctrl = $controller('ReadMeSearchController');
}));
describe('when searching for a user\'s repos', function() {
var httpBackend;
beforeEach(inject(function($httpBackend) {
httpBackend = $httpBackend
httpBackend
.expectGET('https://api.github.com/users/hello/repos?access_token=' + gitAccessToken)
.respond(
{ data: items }
);
}));
afterEach(function() {
httpBackend.verifyNoOutstandingExpectation();
httpBackend.verifyNoOutstandingRequest();
});
var items = [
{
"name": "test1"
},
{
"name": "test2"
}
];
it('adds search results to array of repo names', function() {
ctrl.username = 'hello';
ctrl.doSearch();
httpBackend.flush();
expect(ctrl.gitRepoNames).toEqual(["test1", "test2"]);
});
});
});
当我运行测试时,我收到错误
预期[]等于['test1','test2']。
显然这是因为self.gitRepoNames
没有填补。当我在测试期望之前控制日志ctrl.repoSearchResult
时,我得到了
Object{data: [Object{name: ...}, Object{name: ...}]}
我觉得问题出在哪里,因为在self.repoSearchResult.length
函数的for循环中调用addRepoNames
时,response.data
将被取消定义。
所以我的问题是为什么addRepoNames
在测试中$(document).ready(function () {
$(document).on('change', '#allRolesDD', function () {
var toShow = $("." + $(this).val());
//Below line is the one where I want to get the value where the class name is not equal to the value
// make sure you define your parent here.
var toHide = $(parent).find(":not(." + $(this).val() + ")");
alert($(toHide).html());
toHide.prop('hidden', true);
toShow.show();
});
});
函数中调用数组时不返回数组?
非常感谢任何帮助。
编辑:我应该提一下,当在服务器上运行时,该应用程序运行良好。
答案 0 :(得分:0)
ctrl.doSearch
是一个异步函数。你应该在async way处理它。尝试:
it('adds search results to array of repo names', function(done) {
ctrl.username = 'hello';
ctrl.doSearch().then(function() {
expect(ctrl.gitRepoNames).toEqual(["test1", "test2"]);
done();
});
httpBackend.flush();
});