简体   繁体   English

Angular 4:如何测试订阅中的事件

[英]Angular 4: How to test an event in a subscription

I have a component and in the constructor, I subscribe to an event. 我有一个组件,在构造函数中,我订阅了一个事件。

I send an event via an event service 我通过活动服务发送活动

import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Subject} from "rxjs/Subject";

@Injectable ()
export class EventService {
  private sendSource    = new Subject<string> ();

  sendMessage (message: string) {
    this.sendSource.next (message);
  }
 getMessage (): Observable<any> {
   return this.sendSource.asObservable ();
 }
}

The component contructor: 组件构造器:

constructor (private eventService: EventService) {
    this.subscription = this.eventService.getMessage()
      .subscribe (message => {
        this.menu = message;
      });
}

The .spec file: .spec文件:

it ('should receive event', async (() => {
    eventService = new EventService ();
    eventService.sendMessage ('test');

    fixture.detectChanges ();
    fixture.whenStable ().then (() => {
      expect (component.menu).toBeEqual('test');
    });
}));

My Problem: The this.menu property do not change when I send an event. 我的问题:发送事件时, this.menu属性不会更改。

Can somebody explain my error in reasoning? 有人可以解释我的推理错误吗? Thanks in advance. 提前致谢。

You're instantiating the service in the test, but where / how do you inject it in the component ? 您正在测试中实例化该服务,但是如何/如何将其注入组件中? I suspect you use a different instance. 我怀疑您使用其他实例。

If you've added the service as a provider in the TestBed configuration you can get an instance of it using the injector: 如果您已在TestBed配置中将服务添加为提供程序,则可以使用注入器获取该服务的实例:

const eventService = fixture.debugElement.injector.get(EventService);

And then you can call the sendMessage method and you should get something in the component. 然后,您可以调用sendMessage方法,并且应该在组件中得到一些东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM