我在测试RxJ时遇到问题-TypeError:无法读取未定义的属性'length'

问题描述

我有一个http请求,并对响应进行了一些修改。我无法对此进行正确的测试,请帮助我。我总是在“点击”运算符分支中遇到问题。响应是一个数组。

这是我的简化服务:

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)
          })
        })
        )
      }

这是测试文件:

 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)
  }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)