我在调用控制器函数时遇到访问promise的返回值的问题。调用该函数,然后调用service方法,但返回数据未定义。我是否需要模拟返回值,或者我可以返回实际值,因为它正在运行返回JSON对象的stubby。
我有以下控制器方法(简化为简洁)
function init() {
myService.myServiceMethod()
.then(function(data) {
vm.myvalue = data[0].results;
});
}
vm.init();
和我的测试
$httpBackend.whenGET('/myendpoint').respond(data);
$httpBackend.expectGET('/myendpoint').respond(data);
myService.myServiceMethod().then(function (data) {
console.log(data);
});
// $httpBackend.flush(); // Flush the backend. Important!
scope.$digest();
expect(data).toBeDefined();
答案 0 :(得分:0)
时间问题:
myService.myServiceMethod().then(function (data) {
console.log(data);
// data is filled here, if myServiceMethod() has some response
});
// data is undefined!!!
// Why? The service call is asynchron, so you have to put the expect inside it
expect(data).toBeDefined();
-
myService.myServiceMethod().then(function (data) {
expect(data).toBeDefined();
});