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

Why is my spy test failing?

本文关键字:失败 测试 间谍 我的 为什么      更新时间:2023-09-26

我有以下测试:

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'因此我知道该服务有效。我在单元测试中做错了什么?

我想通了...我的测试$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();
});