您好,我正在尝试测试此 API 调用,但我不知道如何测试响应的状态代码,因为它是真实的(并且必须保持这样)API 调用,而不是模拟调用
这是我正在测试的功能:
export const getDataFromApi = (url) => {
return axios.get(url)
.then(({ data }) => data)
.catch(err => console.log(err.toString()));
}
这是测试:
describe('Read data from API', () => {
test('Get result of the API call', (done) => {
const apiUrl = "https://rickandmortyapi.com/api/character";
getDataFromApi(apiUrl)
.then(data => {
expect(data).toBeDefined();
expect(data.results.length).toBeGreaterThan(0);
done();
});
});
});
如果数据的状态代码是200或者是另一个状态代码,我该如何预期?
我还需要在函数执行后保持完成
吗?我知道我必须回电,但对于这个 promise 我不确定
最佳答案
Axios 有一个single response object在包含 HTTP 状态代码的成功和错误路径中返回。安error is raised if the response is not in the 2xx range .
您可以将状态代码作为 getDataFromApi()
包装函数的返回对象进行探索,但您可能需要完整的响应对象来进行其他检查(例如 header )。我建议完全去掉包装。
如果没有包装器,这里有两种使用 Promise 的不同状态检查,一种用于成功,一种用于失败:
describe('Read data from API', () => {
test('Get successful result of the API call', async() => {
const apiUrl = "https://rickandmortyapi.com/api/character";
await axios.get(apiUrl)
.then(r => {
expect(r.data).toBeDefined();
expect(r.data.results.length).toBeGreaterThan(0);
expect(r.status).toBeGreaterThanOrEqual(200);
expect(r.status).toBeLessThan(300);
})
.catch(e => {
fail(`Expected successful response`);
});
});
test('Get failure result of the API call', async() => {
const apiUrl = "https://rickandmortyapi.com/api/character-bad";
await axios.get(apiUrl)
.then(r => {
fail(`Expected failure response`);
})
.catch(e => {
if (e.response) {
expect(e.response.status).toBeGreaterThanOrEqual(400);
expect(e.response.status).toBeLessThan(500);
} else {
throw e;
}
});
});
});
关于javascript - 使用 Jest 测试对 API 的真实请求的状态代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58660449/