在我升级到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([{}]);
});
});
答案 0 :(得分:3)
如果您将测试重写为
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([{}]);
});
});
由于可观察到的原因,该测试失败,您最终期望的订阅应该可以解决此问题。