Как проверить запрос http с параметрами jest - angular - PullRequest
2 голосов
/ 29 января 2020

Я тестирую сервис angular с Jest.

Я могу издеваться над моим httpClient, но у меня проблема в том, что я не могу протестировать URL с параметром (например: "http://localhost: 8080 / api / feature / num? Id = 25663").

Это мой тестовый код:

describe('MyService', () => {
   let myService: MyService;
   const httpMock = {get: jest.fn(() => of(dataMock))};
   const provide = (mock: any): any => mock;

   beforeEach(() => {
      myService= new MyService(provide(httpMock));
   });

   test('should created', () => {
     expect(myService).toBeTruthy();
   });

   test('should retrieve one user', (done) => {
     const number = 26586;
     const url = 'http://localhost:8080/api/feature/num?number=25663';

     myService.getNumero(number).subscribe( 
       res => {
          expect(httpMock.get).toBeCalledWith(url);
          expect(res.number).toBe(number);
          expect(res.city).toEqual('PARIS');
          done();
     });
   });
});

И в моей консоли у меня есть эта ошибка :

Error: Uncaught [Error: expect(jest.fn()).toBeCalledWith(...expected)

Expected: "http://localhost:8080/api/feature/num?number=25663"
Received: "http://localhost:8080/api/feature/num, {
 "params": {
    "cloneFrom": {
        "cloneFrom": null, 
        "encoder": {}, 
        "map": null, 
        "updates": null
     },
     "encoder": {}, 
     "map": null,
     "updates": [{"op": "a", "param": "number", "value": "25663"}]
   }
 }

1 Ответ

0 голосов
/ 31 января 2020

Обычно мне это нравится

import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

...

describe('MyService', () => {
    let injector: TestBed;
    let httpMock: HttpTestingController;

    beforeEach(() => {
        TestBed.configureTestingModule({
            imports: [HttpClientTestingModule],
            providers: [],
        });
        injector = getTestBed();
        httpMock = injector.get(HttpTestingController);
    });

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

...

    it('should return number and city', () => {
        const expectedResult: {
            number: 26586,
            city: 'PARIS'
        };

        const service : MyService = TestBed.get(MyService);
        service.getNumero(number)
            .pipe(
                first(),
            )
            .subscribe((data) => {
                expect(data).toMatchObject(expectedResult);
            });

        const req = httpMock.expectOne(`http://localhost:8080/api/feature/num?number=25663`);
        expect(req.request.method).toBe('GET');
        req.flush(expectedResult);
    });

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...