Jasmine在测试rxjs ThrowError时超时



摘要:如何在没有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)

我做错了什么?

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

测试应如下所示:

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

";处理错误";测试正确地利用了一个失败的可观察对象是完整的这一事实。

(此外,如果使用观察者对象编写测试,则测试可能更可读:

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

)

最新更新