私はサービスを使用してHttpClientを使用しています。サーバーが応答してエラーが発生した場合は、POSTリクエストを使用してメッセージをフォーマットして再スローします。私はこのシナリオをテストしようとしましたが、テストを模擬しませんでした。 HttpTestingControllerは戻って私のカスタムエラーメッセージを送信していないにもそれがサービスでそれをキャッチして、それを再投げ、適切な方法は、この角度のテスト4 catchと_throwエラーロジックを持つHttpTestingController
サービスコード行うにいただきました:
login(credentials: LoginPayload): Observable<LoginSuccessPayload> {
return this.http.post<LoginSuccessPayload>('/api/auth/signin', credentials)
.map(res => {authUser: res.user})
.catch((error: HttpErrorResponse) => {
if (error.message) {
return _throw(error);
}
return _throw({message: 'Notification.LoginError'});
});
}
今テスト
をbeforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule],
providers: [AuthService]
});
authService = TestBed.get(AuthService);
httpMock = TestBed.get(HttpTestingController);
});
it('should format the error message', (done) => {
const credentials = {userName: 'bob', password: '123'} as LoginPayload;
const mockErrorResponse = {message: 'failed to login'} ;
authService.login(credentials).subscribe(() => {}, err => {
expect(err.message).toEqual(mockErrorResponse.message);
done();
});
const req = httpMock.expectOne('/api/auth/signin');
req.error(new ErrorEvent(mockErrorResponse.message));
httpMock.verify();
});
私はあなたのソリューションが好きで、それも私のために働く。しかし、あなたのコード内のflush()は、サブスクライバにエラーを返します。あなたはエラーをエミュレートするreq.error()を呼び出すはずですか? –
@YakovFainステータスコードなどのプロパティを持つオブジェクトを含む.flush()の第2引数。 –
ステータス200でflush()を試みましたが、それでもサブスクライバのエラーハンドラに行きます。これは私にとってはうまくいく: '' 'req.error(新しいErrorEvent( 'エラーテキスト')); ... .subscribe(()=> {}、 errorResponse => expect(errorResponse.error.type)。toEqual( 'エラーテキスト') ); '' ' –