Javascript 使用Karma模拟来自HTTP Post请求的空阵列响应
我正在使用Karma测试我的平均应用程序,并且在AngularJS(ng mock)中从$httpBackend'expectPOST'方法返回空数组时遇到困难 以下是我正在测试的服务方法:Javascript 使用Karma模拟来自HTTP Post请求的空阵列响应,javascript,angularjs,arrays,unit-testing,karma-runner,Javascript,Angularjs,Arrays,Unit Testing,Karma Runner,我正在使用Karma测试我的平均应用程序,并且在AngularJS(ng mock)中从$httpBackend'expectPOST'方法返回空数组时遇到困难 以下是我正在测试的服务方法: this.getIds = function(path, callback) { // console.log('Sending request to get IDs to the path: ' + path); $http.post('/dropbox/getIds', {path:
this.getIds = function(path, callback) {
// console.log('Sending request to get IDs to the path: ' + path);
$http.post('/dropbox/getIds', {path: path} ).success(function(items) {
if(items.error !== undefined) {
console.log(items.error);
callback('Error with Dropbox API files list request'); // Do not alter string
return;
}
var empty = (items.length === 0) ? true : false;
callback(items, empty);
}).error(function(err) {
console.log(err);
callback('Error making ID request');
});
};
下面是单元测试代码片段:
it('should request Dropbox file IDs at a give path - no errors but empty response', function() {
$httpBackend.expectPOST("/dropbox/getIds").respond({ data: [] });
dropboxService.getIds('path', function(items, empty) {
expect(items).to.deep.equal({data: []});
expect(empty).to.deep.equal(true);
});
});
此测试中的“empty”变量应为true,因为HTTP POST响应是空的“data”数组,但是测试失败,因为“empty”变量实际上为false
有人能告诉我在测试代码或服务方法本身中我做错了什么吗?编辑:
根据Angular文档($http),处理回调返回的方式是不正确的。在您的测试中,项目将被删除
{
data: { data: [] } }
}
我觉得你的三元组应该是
var empty = (items.data.data.length === 0) ? true : false;
然后,您需要将第一个断言更改为
expect(items.data).to.deep.equal({data: []});
不正确的原始帖子:
您需要要求对承诺的解决范围进行摘要。它应该是这样的:
let scope;
beforeEach(() => {
inject($rootScope => {
scope = $rootScope.$new();
});
});
it('should request Dropbox file IDs at a give path - no errors but empty response', function(done) {
$httpBackend.expectPOST("/dropbox/getIds").respond({data: []});
dropboxService.getIds('path', function(items, empty) {
expect(items.data).to.deep.equal({data: []});
expect(empty).to.deep.equal(true);
done();
});
scope.$digest();
});
这不起作用,也不能解决这个问题。我还有其他的测试有回调,我的测试工作正常。问题是模拟空数组,而不是解析回调。对于这个方法,我还有其他的测试,其中返回了一个完整的数组,如果您需要证明的话,这些测试是有效的。