我试图用茉莉花测试我的应用程序,并得到以下问题:
我会计算在我的承诺then
功能的东西。这是我需要测试我的代码的地方。茉莉花测试promise.then功能
这里是我的控制器代码:
TestCtrl.$inject = ["$scope", "TestService"];
/* ngInject */
function TestCtrl($scope, TestService) {
$scope.loadData = function() {
TestService.getData().then(function (response) {
$scope.data = response.data;
$scope.filtered = $scope.data.filter(function(item){
if(item.id > 1000){
return true;
}
return false;
})
});
}
}
我的茉莉花测试代码:
describe('TestService tests', function() {
var $q;
beforeEach(function() {
module('pilot.fw.user');
});
beforeEach(inject(function (_$q_) {
$q = _$q_;
}));
describe('UserController Tests', function() {
beforeEach(inject(function (_$httpBackend_, $rootScope, $controller) {
this.scope = $rootScope.$new();
this.$rootscope = $rootScope;
this.$httpBackend = _$httpBackend_;
this.scope = $rootScope.$new();
var TestServiceMock = {
getData: function() {
var deferred = $q.defer();
var result = [{
"id": 1720,
"user": 1132
},
{
"id": 720,
"user": 132
}, {
"id": 1721,
"user": 1132
}];
deferred.promise.data = result;
deferred.resolve(result);
return deferred.promise;
}
};
this.controller = $controller('TestCtrl', {
'$scope': this.scope,
'TestService': TestServiceMock
});
}));
it('test', function(){
this.scope.loadData();
expect(true).toBeTruthy();
})
});
});
奇怪的,我不明白的是(与控制台日志测试):
- 我的承诺已创建并返回
- 我的承诺数据fu nction被调用,它会调用从TestService的中的getData()函数
- 一切那么函数内部虽然我回来作为解决
所以,我怎么可以测试里面代码的承诺将不会执行然后功能?
感谢您的帮助
它( '测试',功能(完成){ TestServiceMock.getData(),然后(函数(结果){ 的console.log(结果); }); 期望(真).toBeTruthy(); 完成();} ) 我尝试了这种方式,但我isn't控制台日志甚至被称为......像以前一样 同样的问题:/ - 对不起,CodeStyle - 坦克的帮助 –
你调用DONE “当时”之外! 确保'done'是你当时的方法的内部:) –
否则,你在承诺解决之前就执行了,更不知道结果是什么。请注意,在我的示例中,如何将承诺的结果传递给期望方法?这只在解决时才起作用,它在'then'内 –