【问题标题】:Angular2 Unit test Service that Emit value at Constructor Time在构造函数时发出值的Angular2单元测试服务
【发布时间】:2016-03-25 11:39:07
【问题描述】:

为组件编写单元测试,该组件在构造函数中使用带有发射的 Service,如下所示:

@Injectable()
export class Service1 {
  public onService1Done: EventEmitter<any> = new EventEmitter();
  public constructor(...) {
    this.onService1Done.emit(value);
  }
}

我注意到,根据我在 component.spec.ts 中的内容:

beforeEachProviders(() => {
  return [
    provide(Service1, { useClass: MockService1 }),
    Component1
  ];
});

  it("check that XXX", inject(
    [Service1, Component1], (service1: Service1, component1: Component1) => {
    service1.onService1Done.subscribe({ next: () => DoSomething() });
    expect(DoSomething()).toEqual(IsDone);
  }));
});
}

Service1 的构造函数和发射器将在我可以订阅之前在测试中被调用;

有办法避免这种情况吗?在构造函数之前进行订阅?

一如既往,提前致谢。

【问题讨论】:

  • 为什么需要在构造函数中发出?除此之外you shouldn't use EventEmitter in your services。使用普通的 Observables。
  • 所以,如果我理解正确,构造函数中没有 EventEmitter,组件或服务中都没有。但是,在构造函数中使用订阅可能是正确的吗??
  • 当您使用@Output() 时,EventEmitters 在组件中很好。在服务中使用它们是一种不好的做法。除此之外,我的问题仍然存在:为什么要在服务的构造函数中发出一个值进行测试?
  • 事实是我有一个服务(此时可能会说写得不好..),其构造函数中有一个发射;所以...当我测试使用此服务的组件时,我期望的是与真实情况相同的行为,或者更确切地说,该服务也在测试中发出一个值。

标签: unit-testing angular eventemitter


【解决方案1】:

当服务实例由 DI 创建时,我看不出任何东西如何以任何方式订阅来获取此事件。

只是不要在构造函数中发出它,或者至少使用一些setTimeout(...),否则至少同步执行的代码有机会订阅。

【讨论】:

    猜你喜欢
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-02-04
    • 1970-01-01
    • 2019-11-01
    • 1970-01-01
    • 2013-03-23
    • 1970-01-01
    相关资源
    最近更新 更多