angularjs - 使用 ES6 进行 AngularJS 的单元测试

标签 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 = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3b58534e5850155554494952487b544b5e554315585456" rel="noreferrer noopener nofollow">[email protected]</a>';
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()。

知道如何进行测试以等待异步调用在结束之前得到解决吗?

最佳答案

我弄清楚了如何使用异步方法。我所要做的就是在调用异步方法后注入(inject) $rootScope 并使用 $rootScope.$digest() ,即使我没有触及内部的作用域变量我的测试。

关于angularjs - 使用 ES6 进行 AngularJS 的单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37979549/

相关文章:

java - 在 Java 中从 C++ 复制延迟/异步启动策略

jquery - jQuery 自动完成 + AngularJS 的问题

android - apkbuilder 在将 powermock 添加到 android 测试项目时发现重复文件

javascript - Mongoose 、 Node 和异步编码指南

android - 使用android studio进行单元测试时运行哪个测试

c# - 当抽象上下文时,单元测试项目是否应该引用 EF dll

javascript - 如何使用 redux 获取更新后的状态

javascript - 一个 Controller 如何从另一个 Controller 获取值(value)?

javascript - AngularJS,使用 Ng-Repeat 和 Ng-Factory 显示 Json 数据

javascript - 从 AngularJS Controller 获取数据