【问题标题】:Marble testing observable that changes after a method call?大理石测试可观察到在方法调用后发生变化?
【发布时间】:2020-05-21 17:16:49
【问题描述】:

在 Angular 8 中,我有一个带有只读 Observable 属性的服务,它是从包含描述服务状态的字符串的 BehaviorSubject<string> 派生的。服务中还有改变服务状态的方法。

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'); }
}

我想做的是在我的 Jasmine 套件中编写大理石测试,以优雅地测试这个 observable 的值,因为它会发生变化。

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'
    });
  });
});

我尝试了调用beginfinishreset 和调度程序的flush 帮助器的各种组合,但期望总是只报告一个初始值(a 弹珠)而没有其他人。

我错过了什么才能做到这一点?还是弹珠是测试这个的错误方法?

【问题讨论】:

  • 您确定是a 而不是d?不确定 rxjs-marbles(仅使用 jasmine 的),但似乎 '10ms(-)' 不是“在这里工作”,它只能发出最后一个值 - d
  • 假设:调用所有方法后state$只会是最后一个,比如BehaviourSubjectasObservable是单个值
  • @andriishupta 这是可能的,在这种情况下很难说,因为ad 具有相同的值,并且无论我把@放在哪里,报告器都只显示从可观察到的一个值987654338@

标签: angular typescript rxjs jasmine


【解决方案1】:

订阅通过测试助手生成的冷可观察对象似乎有效:

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

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2021-05-20
    • 2021-01-23
    • 2018-01-13
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 1970-01-01
    相关资源
    最近更新 更多