承诺在角度测试

时间:2016-04-21 18:05:51

标签: angularjs jasmine karma-runner

我想在我的控制器类中测试以下方法:

//  getIds() {
//  this.api.getIds()
//    .then((response)=> {
//      this.ids = response.data;
//      this.doSomethingElse();
//    });
//  }

我不确定如何使用茉莉和业力来处理这个承诺。该项目是用ES6编写的。 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
});

如何在运行expect()之前等待承诺完成?

1 个答案:

答案 0 :(得分:2)

首先,您应该使用茉莉提供的<sys/socket.h>回调;见async support in Jasmine

然后,您应该在<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/letsgoog" android:state_pressed="true" /> <item android:drawable="@drawable/letsgob" /> </selector> 上模拟done,以便它返回具有预期值的已解决的承诺。断言应该在调用getIds promise之后完成 - 请参阅完整示例。

api

作为旁注,如果then也是一个承诺,则必须在第一个 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(); }); }); 中返回它,以便您可以测试最终结果。