使用 angular jasmine returns undefined 测试获取请求
Testing a get request using angular jasmine returns undefined
我有一个简单的方法可以构建一个随机 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'
const 响应 = [{ 数据:'string'}]
我不知道我做错了什么。
您的期望检查将在您执行 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)
})
我有一个简单的方法可以构建一个随机 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' const 响应 = [{ 数据:'string'}]
我不知道我做错了什么。
您的期望检查将在您执行 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)
})