简体   繁体   English

rxjs 如何期望 observable 抛出错误

[英]rxjs how to expect an observable to throw error

In my TypeScript app I have a method that return an rxjs Observable which, in a certain case, can return throwError :在我的 TypeScript 应用程序中,我有一个返回 rxjs Observable 的方法,在某些情况下,它可以返回throwError

import { throwError } from 'rxjs';

// ...

getSomeData(inputValue): Observable<string> {
  if (!inputValue) {
    return throwError('Missing inputValue!');
  }

  // ...
}

how can I write a test to cover this specific case?我如何编写测试来涵盖这个特定案例?

You can test it using RxJS Marble diagram tests.您可以使用 RxJS Marble 图表测试来测试它。 Here's how:就是这样:

const getSomeData = (inputValue: string): Observable<string> => {
  if (!inputValue) {
    return throwError('Missing inputValue!');
  }

  // e.g.
  return of(inputValue);
};

describe('Error test', () => {

  let scheduler: TestScheduler;

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

  it('should throw an error if an invalid value has been sent', () => {
    scheduler.run(({ expectObservable }) => {

      const expectedMarbles = '#'; // # indicates an error terminal event

      const result$ = getSomeData(''); // an empty string is falsy

      expectObservable(result$).toBe(expectedMarbles, null, 'Missing inputValue!');
    });
  });

  it('should emit an inputValue and immediately complete', () => {
    scheduler.run(({ expectObservable }) => {

      const expectedMarbles = '(a|)';

      const result$ = getSomeData('Some valid string');

      expectObservable(result$).toBe(expectedMarbles, { a: 'Some valid string' });
    });
  });
});

For more info on how to write these tests, please take a look at this link .有关如何编写这些测试的更多信息,请查看此链接

I imagine your full case resembles something like this我想你的完整案例类似于这样的东西

// first there is something that emits an Observable
export function doSomethingThatReturnsAnObservable() {
  return createSomehowFirstObservable()
  .pipe(
     // then you take the data emitted by the first Observable 
     // and try to do something else which will emit another Observable
     // therefore you have to use an operator like concatMap or switchMap
     // this something else is where your error condition can occur
     // and it is where we use your getSomeData() function
     switchMap(inputValue => getSomeData(inputValue))
  );
}
}

// eventually, somewhere else, you subscribe
doSomethingThatReturnsAnObservable()
.subscribe(
   data => doStuff(data),
   error => handleError(error),
   () => doSomethingWhenCompleted()
)

A test for the error condition could look something like this错误条件的测试可能看起来像这样

it('test error condition'), done => {
   // create the context so that the call to the code generates an error condition
   .....
   doSomethingThatReturnsAnObservable()
   .subscribe(
      null, // you are not interested in the case something is emitted
      error => {
        expect(error).to.equal(....);
        done();
      },
      () => {
        // this code should not be executed since an error condition is expected
        done('Error, the Observable is expected to error and not complete');
      }
   )
})

In addition to lagoman's answer.除了拉戈曼的回答。 You could simplify the way to get the testScheduler.您可以简化获取 testScheduler 的方法。

describe('Error test', () => {  
  it('should throw an error if an invalid value has been sent', () => {
    getTestScheduler().run(({ expectObservable }) => { // getTestScheduler from jasmine-marbles package

      const expectedMarbles = '#'; // # indicates an error terminal event

      const result$ = getSomeData(''); // an empty string is falsy

      expectObservable(result$).toBe(expectedMarbles, null, 'Missing inputValue!');
    });
  });

  it('should emit an inputValue and immediately complete', () => {
    getTestScheduler().run(({ expectObservable }) => {

      const expectedMarbles = '(a|)';

      const result$ = getSomeData('Some valid string');

      expectObservable(result$).toBe(expectedMarbles, { a: 'Some valid string' });
    });
  });
});

Another way is to check that the operator thows an error is to pipe it like below.另一种方法是检查操作员是否显示错误,如下所示对其进行管道传输。 I assume that you are using Chai.我假设您正在使用 Chai。

import { catchError } from 'rxjs/operators';

it('must throw an error',  done => {
     getSomeData().pipe(catchError((e) => [e])).subscribe(e => {
        expect(e).to.be.an.instanceof(Error);
        done();
      })
})

Source How to test an RxJS operation that throws an error Source 如何测试抛出错误的 RxJS 操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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