[英]promise testing in angular
I want to test the following method in my controller class: 我想在控制器类中测试以下方法:
// getIds() {
// this.api.getIds()
// .then((response)=> {
// this.ids = response.data;
// this.doSomethingElse();
// });
// }
I'm not sure how to handle the promise using jasmine and karma. 我不确定如何使用茉莉花和业力来兑现诺言。 The project is written in ES6.
该项目是用ES6编写的。
api.getIds()
returns a $http.get(). api.getIds()
返回$ http.get()。
beforeEach(function() {
inject(function($controller, $rootScope, _api_) {
vm = $controller('MainController', {
api: _api_,
$scope:$rootScope.$new()
});
});
});
beforeEach(function () {
vm.getIds();
});
it('should set the ids', function () {
expect(vm.ids).toBeDefined(); //error
});
How do I wait for the promise to complete before running the expect() ? 如何在运行Expect()之前等待诺言完成?
First of all, you should use the done
callback provided by the jasmine; 首先,您应该使用茉莉花提供的
done
回调; see async support in Jasmine . 请参阅Jasmine中的异步支持 。
Then, you should mock your getIds
on the api
so that it returns a resolved promise with an expected value. 然后,您应该在
api
上模拟您的getIds
,以便它返回具有期望值的已解决的Promise。 The asserts should be done after the then
promise is called - se bellow the full example. 断言应该在
then
promise调用之后完成-在下面的完整示例中。
beforeEach(function () {
var $q, vm, api, $controller, $rootScope;
inject(function (_$controller_, _$rootScope_, _$q_) {
$q = _$q_;
$controller = _$controller_;
$rootScope = _$rootScope_;
api = jasmine.createSpyObj('api', ['getIds']);
api.getIds.and.returnValue($q.when([]));
vm = $controller('MainController', {
api: api,
$scope: $rootScope.$new()
});
});
});
it('should set the ids', function (done) {
vm
.getIds()
.then(function (ids) {
expect(ids).toBeDefined();
// add more asserts
done();
});
});
As a side note, if the this.doSomethingElse();
附带说明一下,如果
this.doSomethingElse();
is a promise too, you have to return it in the first then
so that you can test the final result. 也是一个承诺,您必须先返回它,
then
才能测试最终结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.