为什么我的间谍测试失败了?

时间:2016-01-29 14:31:29

标签: javascript angularjs jasmine ecmascript-6 angular-promise

我有以下测试:

beforeEach(inject(($document, _DirectiveReadyService_) => {
  DirectiveReadyService = _DirectiveReadyService_;
  foo = jasmine.createSpy('foo');
}));

it('should resolve `foo` subscriber when `foo` is published', () => {
  DirectiveReadyService.subscribe('foo').then(foo);
  DirectiveReadyService.publish('foo');

  expect(foo).toHaveBeenCalled();
});

我的DirectiveReadyService看起来像:

export class DirectiveReadyService {
  constructor($q, $rootScope) {
    'ngInject';

    this._$q = $q;
    this._directives = {};

    const resetDirectives = $rootScope.$on('$stateChangeStart', () => {
      this._directives = {};
    });
    $rootScope.$on('$destroy', resetDirectives);
  }

  publish(type, ...params) {
    if (this._directives[type]) {
      console.log('publish', type);
      this._directives[type].resolve(params);
    }
  }

  subscribe(...types) {
    const done = [];

    console.log('subscribe', types);

    types.forEach(type => {
      this._directives[type] = this._directives[type] || this._$q.defer();
      done.push(this._directives[type].promise);
    });

    return this._$q.all(done).then(result => {
      console.log('done', result);
      return result;
    });
  }
}

当我运行测试时,我在控制台中看到以下内容:

'subscribe', ['foo']
'publish', 'foo'

但是我从来没有得到'done',我的测试失败了。但是,针对此服务进行开发并在浏览器控制台中预览会一直记录到'done',因此我知道该服务有效。我在单元测试中做错了什么?

1 个答案:

答案 0 :(得分:0)

我想通了......我的测试失踪了$rootScope.$apply();。有了这个,诺言就会解决。

beforeEach(inject(($document, _$rootScope_, _DirectiveReadyService_) => {
  DirectiveReadyService = _DirectiveReadyService_;
  foo = jasmine.createSpy('foo');
  $rootScope = _$rootScope_;
}));

it('should resolve `foo` subscriber when `foo` is published', () => {
  DirectiveReadyService.subscribe('foo').then(foo);
  DirectiveReadyService.publish('foo');

  $rootScope.apply();

  expect(foo).toHaveBeenCalled();
});