【问题标题】:Jasmine times out when testing rxjs ThrowErrorJasmine 在测试 rxjs ThrowError 时超时
【发布时间】:2022-01-13 21:59:10
【问题描述】:

总结:如何在 Jasmine 超时的情况下测试 rxjs ThrowError?


我正在测试一项可以返回已完成的 Observable 或错误的服务。出于测试目的,我们可以用这个服务来表示它:

import { Observable, of, throwError } from 'rxjs';

export class MyService {
  foo(shouldError: boolean): Observable<any> {
    if (shouldError) {
      return throwError('');
    } else {
      return of();
    }
  }
}

为了测试这段代码,我做了以下测试:


describe('MyService', () => {
    let service: MyService;

    beforeEach(() => {
        TestBed.configureTestingModule({});
        service = TestBed.inject(MyService);
    });

    it('handles observable', (done) => {
        const shouldError = false;
        service.foo(shouldError).subscribe(
            (_) => done(),
            (_) => done.fail()
        );
    });

    it('handles error', (done) => {
        const shouldError = true;
        service.foo(shouldError).subscribe(
            (_) => done.fail(),
            (_) => done()
        );
    });
}

但是,这段代码最终导致 Jasmine 超时:

Error: Timeout - Async function did not complete within 5000ms (set by jasmine.DEFAULT_TIMEOUT_INTERVAL)

我做错了什么?

【问题讨论】:

    标签: typescript rxjs jasmine


    【解决方案1】:

    我犯的错误是测试订阅者使用了 next() 块,因为我返回了一个完整的 observable,所以不会触发它。

    测试应该写成如下:

        it('handles observable', (done) => {
            const shouldError = false;
            service.foo(shouldError).subscribe(
                (_) => done.fail('unexpected next'),
                (_) => done.fail('unexpected error'),
                () => done()
            );
        });
    
        it('handles error', (done) => {
            const shouldError = true;
            service.foo(shouldError).subscribe(
                (_) => done.fail('unexpected next'),
                (_) => done(),
                () => done.fail('unexpected complete')
            );
        });
    

    “处理错误”测试正确地利用了失败的 observable 已完成这一事实。

    (此外,如果使用observer object 编写测试,则可能更具可读性:

            service.foo(shouldError).subscribe({
                next: (_) => done.fail('unexpected next'),
                error: (_) => done(),
                complete: () => done.fail('unexpected complete')
            });
    

    )

    【讨论】:

      猜你喜欢
      • 2014-09-02
      • 2014-09-23
      • 1970-01-01
      • 1970-01-01
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-06-08
      • 2019-10-13
      相关资源
      最近更新 更多