单元测试AngularJS承诺与ES6

时间:2016-06-22 22:56:25

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

我试图在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()。

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

1 个答案:

答案 0 :(得分:2)

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