【问题标题】:Why is my spy test failing?为什么我的间谍测试失败了?
【发布时间】:2016-01-29 14:31:28
【问题描述】:

我有以下测试:

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

【问题讨论】:

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


    【解决方案1】:

    我想通了...我的测试丢失了$rootScope.$apply();。这样,promise 就解决了。

    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();
    });
    

    【讨论】:

      猜你喜欢
      • 2014-08-14
      • 1970-01-01
      • 1970-01-01
      • 2016-10-05
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      相关资源
      最近更新 更多