在我升级到Angular的新版本之后,我以前工作过的一个测试打破了,我不知道为什么。即我有一个记录错误的功能:
import { Observable, of } from 'rxjs';
export function handleError<T>(operation='operation', result?: T) {
return (error: any): Observable<T> => {
console.error(error);
console.info(`${operation} failed: ${error.message}`);
return of(result as T);
}
}
我测试它:
it('#handleError return function should return an object', () => {
let errorFunction = handleError('dummyFetch', [{}]);
expect(typeof errorFunction({ message: 'Something went wrong.'})).toEqual('object');
expect(errorFunction({ message: 'Something went wrong.'})).toEqual(of([{}]));
});
失败的行是expect(errorFunction({ message: 'Something went wrong.'})).toEqual(of([{}]));
并报告错误:Expected $._subscribe = Function to equal Function.
。由于异步错误功能,测试是否失败?
编辑:这是我解决的解决方案:
it('#handleError return function should return an object', () => {
let errorFunction = handleError('dummyFetch', [{}]);
expect(typeof errorFunction({ message: 'Something went wrong.' })).toEqual('object');
let error = errorFunction({ message: 'Something went wrong.' });
error.subscribe(value => {
expect(value).toEqual([{}]);
});
});
如果你把测试重写为
it('#handleError return function should return an object', () => {
let errorFunction = handleError('dummyFetch', [{}]);
expect(typeof errorFunction({ message: 'Something went wrong.'})).toEqual('object');
errorFunction.subscribe((result) => {
expect(result).toEqual([{}]);
});
});
此测试由于可观察性而失败,并且您的最终期望中的订阅应该解决此问题。