首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用catch和_throw误差逻辑测试角4_throw

用catch和_throw误差逻辑测试角4_throw
EN

Stack Overflow用户
提问于 2017-10-12 20:25:48
回答 3查看 3.6K关注 0票数 1

我让服务使用HttpClient使用POST请求,如果服务器响应并出错,我需要捕获它格式化消息并重新抛出它。我试过测试这个场景,但没有模拟测试。HttpTestingController没有将我的自定义错误消息发回,也没有在服务上捕获它并重新抛出它,那么如何做才是正确的呢?

服务代码:

代码语言:javascript
复制
 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'});
             });

 }

现在是测试

代码语言:javascript
复制
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();
});
EN

回答 3

Stack Overflow用户

发布于 2017-12-30 14:26:50

我知道我要迟到了,但我想无论如何我都会回答那些像我一样遇到这种事的人。我发现围绕这个错误情况的完整的缺乏文件在angular.io上是疯狂的。“自己想办法”,我猜?

我采用的Anyway...the方法是完全避免使用.error(),因为它似乎不像使用.flush()那么容易,文档中的状态可以用于成功的和不成功的响应。

下面是我将如何更新您的代码以使用刷新:

代码语言:javascript
复制
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 => {
        // NOTE: err.error.message
        expect(err.error.message).toEqual(mockErrorResponse.message);
        done();
    });

    const req = httpMock.expectOne('/api/auth/signin');
    req.flush({message: mockErrorResponse.message}, {status: 400, statusText: ''});

    httpMock.verify();
});

@angular/common/http中的Http (而不是@angular/http中的Http)相比,使用@angular/common/http中的err.error更新的一个令人讨厌的部分是,错误消息现在是subscribe()err.error的属性,而不是err本身的属性。

因此,如果您和我一样,并且从一个升级到另一个,那么所有对err.message的引用都必须更新为err.error.message。我希望这能帮到你。

票数 4
EN

Stack Overflow用户

发布于 2017-10-13 06:18:30

我有一些对我有用的建议。

首先,我要替换这个:

代码语言:javascript
复制
authService = TestBed.get(AuthService);
httpMock = TestBed.get(HttpTestingController);

在这方面:

代码语言:javascript
复制
const testBed = getTestBed();
authService = testBed.get(AuthService);
httpMock = testBed.get(HttpTestingController);

我认为这里的要点是,您无法真正访问测试床。

我还想核实一下,您的请求是POST请求,包括以下内容:

代码语言:javascript
复制
expect(req.request.method).toBe("POST");

这些是我第一次想到的东西。

票数 0
EN

Stack Overflow用户

发布于 2019-08-09 04:07:45

我尝试了链接的角度文档方法,它使用req.error对我起作用。希望这有帮助..。

代码语言:javascript
复制
it('should handle an error', inject([HttpClient, HttpTestingController], (http: HttpClient, httpMock: HttpTestingController) => {

    http.get<any>('http://localhost:4200/api/data').subscribe(
        response => fail('should fail with a 403 error'),
        error => {
            expect(error.status).toBe(403);
        }
    );

    // Mocking rejects with a 403 error
    let mockRequest = httpTestingController.expectOne(req =>  
                        req.url === 'http://localhost:4200/api/data');
    let error = new ErrorEvent('ERROR');
    mockRequest.error(error, { status: 403 ,statusText: 'Invalid access.'});

    mockHttp.verify();
}));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46718299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档