Angular ngOnInit测试订阅

时间:2017-10-21 22:45:02

标签: angular unit-testing angular2-observables

我正在尝试测试一个简单的调用,该调用将发送到我的dialogService并返回一个observable。触发该方法时,将设置组件上的本地属性。我的代码如下。任何帮助将不胜感激,我已经尝试了一切我无法让它工作。

Dialogue.component.ts

export class DialogueComponent implements OnInit {
  public showDialogue: boolean;
  public reason: string;

  constructor(private dialogueService: DialogueService) { }

  public closeDialogue() {
    this.showDialogue = !this.showDialogue;
  }

  public ngOnInit() {
    this.dialogueService.showDialogue.subscribe((shouldShow: boolean) => {
      this.showDialogue = shouldShow;
    });
    this.dialogueService.reason.subscribe((reason) => {
      this.reason = reason;
    });
  }
}

Dialogue.component.spec.ts

describe('DialogueComponent', () => {
  beforeEach((() => {
    resetSpies();

    TestBed.configureTestingModule({
      declarations: [DialogueComponent],
      imports: [RouterTestingModule],
      providers: [DialogueService]
    }).compileComponents();
  }));

  it('should set the subscriptions and update the component properties accordingly', async(() => {
    const fixture = TestBed.createComponent(DialogueComponent);
    const dialogueService = TestBed.get(DialogueService);
    spyOn(dialogueService, 'showDialogue').and.returnValue(Observable.of({ foo: 'bar' }));

    // I have used a tick() here using fakeAsync but no luck either

    expect(fixture.componentInstance.showDialogue).toEqual(false);
  }));

});

0 个答案:

没有答案
相关问题