【问题标题】:How to test with the marble approach when the returm is a EMPTY observable in effect?当返回是一个有效的 EMPTY 可观察对象时,如何使用大理石方法进行测试?
【发布时间】:2020-08-28 19:27:10
【问题描述】:

我正在使用 rxjs 中的 EMPTY 来处理 catchError,为了通过失败场景,预期的正确值是多少。

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { EMPTY } from 'rxjs';
import { map, mergeMap, catchError } from 'rxjs/operators';
import { MoviesService } from './movies.service';

@Injectable()
export class MovieEffects {

  loadMovies$ = createEffect(() => this.actions$.pipe(
    ofType('[Movies Page] Load Movies'),
    mergeMap(() => this.moviesService.getAll()
      .pipe(
        map(movies => ({ type: '[Movies API] Movies Loaded Success', payload: movies })),
        catchError(() => EMPTY)
      ))
    )
  );

  constructor(
    private actions$: Actions,
    private moviesService: MoviesService
  ) {}
}


// unit test

it('should return a empty observable', () => {
   this.moviesServiceSpy.and.return(throwError('Error in service'));

   action$ = hot('a', a: { loadMovies() });

   const expected = cold('|');

   expect(loadMovies$).toBeObservable(expected);

})

【问题讨论】:

    标签: javascript jasmine rxjs5 ngrx-effects rxjs-marbles


    【解决方案1】:

    我自己也遇到了这个问题,偶然发现了你的问题。我想我有一个答案:因为EMPTY immediately completes 我认为这意味着0 时间过去了。 (编辑:这是错误的!)

    EMPTYempty() 本身将匹配 cold('|')hot('|')。请阅读以下内容,了解它与cold('')hot('') 的效果匹配的原因。 (参见this RxJS documentation 的示例部分,其中也显示了这一点。)

    similar answer on another question 确认,现在引用原因:

    cold('|') 中的管道字符表示可观察流的完成。但是,您的效果不会完成。 empty() observable 确实完成了,但是从 switchMap 返回 empty() 只会看到 observable 合并到 effect observable 的流中 - 它没有完成 effect observable。

    因此,虽然EMPTY(或empty())被记录为立即完成,但在效果中使用它的最终结果表明效果永远不会完成。

    将此答案插入您的示例中:

    it('should return a empty observable', () => {
       this.moviesServiceSpy.and.return(throwError('Error in service'));
    
       action$ = hot('a', a: { loadMovies() });
    
       const expected = cold('');
    
       expect(loadMovies$).toBeObservable(expected);
    
    })
    

    为了好玩,下面的测试也通过了:

    it('should match EMPTY with a single tick pipe marble', () => {
       expect(EMPTY).toBeObservable(cold('|'));
       expect(EMPTY).toBeObservable(hot('|'));
    
       // empty() is deprecated, but these assertions still pass.
       expect(empty()).toBeObservable(cold('|'));
       expect(empty()).toBeObservable(hot('|'));
    });
    

    【讨论】:

      猜你喜欢
      • 2021-01-23
      • 2019-02-18
      • 2017-07-12
      • 2020-09-14
      • 1970-01-01
      • 2017-04-19
      • 2020-05-21
      • 2019-04-23
      • 1970-01-01
      相关资源
      最近更新 更多