【问题标题】:Unit testing AngularJS promises with ES6使用 ES6 对 AngularJS 承诺进行单元测试
【发布时间】:2016-10-25 01:48:28
【问题描述】:

我正在尝试在 AngularJS 服务中测试一个异步方法,该方法在内部使用 Jasmine 和 Karma 调用另一个异步函数。

我的服务如下所示:

export default class SearchUserAPI {

  constructor(BaseService, $q) {
    this.q_ = $q;
    this.service_ = BaseService;
  }

  isActive(email) {
    const params = {'email': email};

    return this.service_.getUser(params).then(isActive => {
      // This part cannot be reached.
      console.log('Is Active');
      // I need to test the following logic.
      return isActive ? true : this.q_.reject(`User ${email} is not active.`);
    });
  }
}

这是我的测试的样子:

import SearchUserApi from './api.service';

let service,
    mockedService,
    $q;

const email = 'chuck.norris@openx.com';
const expectedParams = {email: email};

describe('Search API unit tests', function() {

  beforeEach(inject(_$q_ => {
    $q = _$q_;
    mockedService = {};

    service = new SearchUserApi(mockedService, $q);
  }));

  // This test passes, but it doesn't reach the logging statement in main method.
  it('is verifying that Chuck Norris should be active', () => {
    // Trying to mock getUser() to return a promise that resolves to true.
    mockedService.getUser = jasmine.createSpy('getUser').and.returnValue($q.when(true));

    service.isActive(email).then(result => {
      // The following should fail, but since this part is called asynchronously and tests end before this expression is called, I never get an error for this.
      expect(result).toBe(false);
    });
    // This test passes, but I'm not too sure how I can verify that isActive(email) returns true for user.
    expect(mockedService.getUser).toHaveBeenCalledWith(expectedParams);
  });
});

我在很多教程中看到,他们谈论使用 $scope 并应用来查看范围变量是否已更改。但就我而言,我没有操纵任何实例(范围)变量来使用 $scope.apply()。

知道如何让测试在异步调用结束之前等待它们得到解决吗?

【问题讨论】:

    标签: angularjs unit-testing asynchronous promise ecmascript-6


    【解决方案1】:

    我想出了如何通过异步方法。我所要做的就是在调用异步方法后注入 $rootScope 并使用 $rootScope.$digest(),即使我没有触及内部的范围变量我的测试。

    【讨论】:

    猜你喜欢
    • 2013-12-23
    • 2018-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2013-09-25
    • 1970-01-01
    相关资源
    最近更新 更多