mercredi 21 octobre 2020

I have a problem with testing RxJs - ( TypeError: Cannot read property 'length' of undefined )

I have a http request and some modification with the response. I couldn't make a correct test for it, please help me out. I always have problem in the "tap" operator branch. The response is an array.

Here is my simplified service:

getRequest() {
    const otherIds = []
    return this.http
      .get<any>(url)
      .pipe(
        map(response => { // array
          return response
            .map(id=> {
              return id
            })
            .sort((a, b) => {
              debugger
              return a > b ? 1 : -1
            })
        }),
        tap(response => {    
          response.forEach(element => {
             otherIds.push(element.id)
          })
        })
        )
      }

Here is the test file:

 it('getRequest: should get request', getRequest)

  function getRequest() {
    let responseIds: any
    let otherIds = []

   service.getRequest().subscribe(data => {
      responseIds= data
      data.forEach(id => otherIds.push(id))
      expect(otherIds.length).toBeGreaterThan(0)
    }
    httpMock
      .expectOne({ url, method: 'GET' })
      .flush(idMock) // idMock is an array with 3 items

    expect(responseIds.length).toBe(3)
  }

Aucun commentaire:

Enregistrer un commentaire