简体   繁体   中英

Testing a simple service that uses .next, .subscribe in Angular 4 using Karma / Jasmin

I have a simple service in my app like so...

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

@Injectable()
export class WizardDialogNavigationService {

  public navAction$: Observable<any>;
  private navActionSubject: Subject<any> = new Subject();

  constructor() {
    this.navAction$ = this.navActionSubject.asObservable();
  }

  public navAction(action: string): void {
    this.navActionSubject.next(action);
  }
}

It's not the most complex service, it just allows me to communicate between components. Now I need to test it, I have to admit I know very little about testing. I just want to check that when WizardDialogNavigationService.navAction is called the navAction$ Observable contains the passed string, so I wrote the following...

import {TestBed, inject, async} from '@angular/core/testing';
import {Observable} from 'rxjs/Rx';
import {expect} from 'chai';
import * as sinon from 'sinon';
import {WizardDialogNavigationService} from './wizard-dialog-navigation.service';

describe('WizardDialogNavigationService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [WizardDialogNavigationService]
    });
  })

  describe('navAction$ Observable', () => {

    let sut: WizardDialogNavigationService; // sut = Service Under Test

    beforeEach(inject([WizardDialogNavigationService], (service: WizardDialogNavigationService) => {
      sut = service;
    }));

    it('should be the last passed value', async(() => {
      const resultList = [];
      sut.navAction('TestString');

      sut.navAction$.subscribe((result) => resultList.push(result));
      console.log(resultList); // output is []
      expect(resultList.indexOf('TestString')).to.equal(0);
    }));
  });
});

I think I am going about this wrong as the resultList array doesn't contain the passed value? It's as if the .next() .subscribe() isn't being called / ran. If anyone can tell me where I am going wrong I would appreciate it.

You need a BehaviorSubject which will return the already stored value, if you subscribe to it directly.

So you can change the Subject to a BehaviorSubject and subscribe to it and it will work.

Doc:

https://github.com/ReactiveX/rxjs/blob/master/doc/subject.md#behaviorsubject

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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