【问题标题】:Testing a get request using angular jasmine returns undefined [closed]使用 Angular jasmine 测试获取请求返回未定义 [关闭]
【发布时间】:2020-12-11 18:45:44
【问题描述】:

我有一个简单的方法可以构造一个随机 url,例如 (https://wqwqw.com/121212 ) 121212是随机生成的。

getCall(url) {
   this.http.get(url)
}

在我的测试中我有

  it('test get', async (() => {
    let res;
    service.getCall('a').toPromise().then(x => {
      res = x
    })
   
    expect(res).toEqual(response) // res is undefined 
 
    const request = httpMock.expectOne('a') // errorr
    request.flush(res)
  }))

我期待随叫随到,但由于 url 是随机的,我不知道它是什么,但无论我说什么,它都说''expect 1 got none' 常量响应 = [{ 数据:'字符串'}]

我不知道我做错了什么。

【问题讨论】:

    标签: angular typescript jasmine karma-jasmine


    【解决方案1】:

    您的期望检查将在您执行service.getCall 后立即运行,因此在 res 有机会被定义之前。您需要确保在您的回调中运行测试检查(然后确保您的 Jasmine 测试等到该回调完成后再退出),或者明确指定您要等待调用完成。

    由于您已经为测试指定了异步函数,我建议使用 await,这似乎也是 Jasmine docs 中的首选方式。

      it('test get', async () => {
        const res = await service.getCall('a').toPromise()
       
        expect(res).toEqual(response)
     
        const request = httpMock.expectOne('a') // errorr
        request.flush(res)
      })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-31
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      相关资源
      最近更新 更多