Marble testing observable that changes after a method call?

淺唱寂寞╮ 提交于 2021-01-28 09:34:01

问题


In Angular 8, I have a service with a readonly Observable property, spawned from a BehaviorSubject<string> that contains a string describing the service's state. Also in the service are methods that change the state of the service.

export class StateService {
  private _state = new BehaviorSubject<string>('before');

  readonly state$ = this._state.asObservable();

  constructor () { }

  begin() { this._state.next('during'); }

  finish() { this._state.next('after'); }

  reset() { this._state.next('before'); }
}

What I want to do is write marble tests in my Jasmine suite to elegantly test the value of this observable as it would change.

let scheduler: TestScheduler;

beforeEach(() => {
  scheduler = new TestScheduler((actual, expected) => {
    expect(actual).toEqual(expected);
  });
});

it('should flow states correctly', () => {
  scheduler.run(({expectObservable, flush}) => {
    const svc = setupSvc(); //Call to a function in the suite that sets up the StateService

    svc.begin();
    svc.finish();
    svc.reset();

    flush();

    expectObservable(svc.state$).toBe('a-b-c-d', {
      a: 'before',
      b: 'during',
      c: 'after',
      d: 'before'
    });
  });
});

I've tried varying combinations of calling begin, finish, reset, and the scheduler's flush helper, but the expectation always reports just the one initial value (the a marble) and no others.

What am I missing to be able to pull this off? Or are marbles the wrong way to go about testing this?


回答1:


Subscribing to a cold observable produced via the test helper seems to work:

it('should flow states correctly', () => {
  scheduler.run(({ expectObservable, cold }) => {
    const svc = new StateService();

    cold('--a-b-c', {
      a: 'begin',
      b: 'finish',
      c: 'reset'        
    }).subscribe(methodName => {
      svc[methodName]();
    })

    expectObservable(svc.state$).toBe('a-b-c-d', {
      a: 'before',
      b: 'during',
      c: 'after',
      d: 'before'
    });
  });
});

Stackblitz



来源:https://stackoverflow.com/questions/60081765/marble-testing-observable-that-changes-after-a-method-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!