lundi 3 juin 2019

how to do unit testing with http testing controller

It's my first time unit testing and honestly I don't quite get how it works and the purpose of doing this.

I'm trying to test the angular service function that requests a JWT token by sending valid/invalid "code". So in the request i send {"code": "something"} and it returns either JWT token on success or an error(Actually, in both case it returns 200 OK but only the body changes. like on success it returns {"token":"something", "expireDate":"something"}, and on fail {"error":"message"} like this). So here I'm trying to mock fail response by

req.error(new ErrorEvent("ERROR"));

What I don't get is, no matter how I mock the error or change the method followed by expect The unit testing passes. Like If I do

expect(result).toBe("random string");

It still passes.

Also, what I don't get is why the

service.getTmwJwt(dummyCode).subscribe(result => {
    expect(result).toThrow();
  });

expect(result) comes before the req.error / flush? since req.error mocks the bad response. Shouldn't it come first than assert values?

Here's the original testing code.

it('should return an error observable<Authorization> on error response', 
( ) => {
const dummyCode = 'invalid';

service.getJwt(dummyCode).subscribe(result => {
  expect(result).toThrow();
});
//will have to check the body since error also returns 200 ok 
//instead of req.flush, do req.error
const req = httpMock.expectOne(`${CONST.TOKEN_URL}`);
expect(req.request.method).toBe('POST');

req.error(new ErrorEvent("ERROR_BAD_CODE_REQUEST"));
httpMock.verify();



});

Here's the service function i'm testing on.

public getJwt(code: any): Observable<Authorization> {
// const url = 'https://actualURL';
return this.http
  .post<any>(CONST.TOKEN_URL, { code: "code"}) 
  .pipe(catchError(this.handleError)); //returns failure observable
}

It really sounds like dumb but I think I'm missing some concept. Thanks.

Aucun commentaire:

Enregistrer un commentaire