角度单元测试失败HttpClient请求

时间:2017-11-25 18:47:19

标签: angular unit-testing

我试图对我有责任进行http调用的服务进行单元测试。我可以测试成功请求,但是当响应的状态代码与200不同时,我无法进行测试。

例如,让我们说请求返回404状态,然后我无法正确测试。

这是我的服务:

@Injectable()
export class ApiService {
    constructor(
        private _http: HttpClient,
        private _router: Router,
        private _toast: ToastsManager,
        private _auth: AuthService,
    ) { }

    public apiGet(url: string) {
        return this._http
            .get(url)
            .catch(this.handleError.bind(this));
    }

    private handleError(error) {
        if (error.status === 401) {
            this._auth.logout();
            return Observable.throw(error);
        }

        if (error.status === 404) {
            this._router.navigateByUrl('not-found');
            return Observable.throw(error);
        }

        if (error.error && error.error.message) {
            this._toast.error(error.error.message);
        } else {
            this._toast.error('Something went wrong');
        }

        return Observable.throw(error);
    }
}

这就是我测试的方式:

describe('ApiService', () => {
    let service: ApiService;
    let backend: HttpTestingController;

    const mockSuccessResponse = { value: '123', name: 'John' };
    const mockSuccessStatus = { status: 200, statusText: 'Ok' };

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [
                MockModule,
                HttpClientTestingModule,
            ],
            providers: [
                ApiService,
            ]
        });

        service = TestBed.get(ApiService);
        backend = TestBed.get(HttpTestingController);
    });

    it('should call the apiGet() function with success', () => {
        service.apiGet('mock/get/url').subscribe(response => {
            expect(response).toEqual(mockSuccessResponse);
        });

        const req = backend.expectOne('mock/get/url');

        expect(req.request.url).toBe('mock/get/url');
        expect(req.request.method).toBe('GET');

        req.flush(mockSuccessResponse, mockSuccessStatus);
    });

    it('should execute handleError function on status different of 200', () => {
        service.apiGet('mock/error/url').subscribe(response => { }, error => {
            // Handle the error cases here (?)
        });

        const req = backend.expectOne('mock/error/url');

        req.flush(null, { status: 404, statusText: 'Not Found' });
    });

    afterEach(() => {
        backend.verify();
    });
});

我不知道如何从这里继续。如果我尝试执行expect(service.handleError()).toHaveBeenCalled();之类的操作,我会收到handleError is a private method之类的错误。

我还需要测试logout()上的authService函数是否会被调用,或者如果路径在404错误上更改为not-found

如果能够测试那些响应状态与200不同的情况,我该怎么办?

0 个答案:

没有答案