使用Jest测试对API的真实请求的状态码

时间:2019-11-01 13:57:50

标签: javascript rest api jestjs

您好,我正在尝试测试此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还是其他状态码?

我是否还需要在执行函数后离开那个done?我知道必须使用回叫功能,但我不确定是否会保证

1 个答案:

答案 0 :(得分:2)

Axios 在成功和错误路径中都返回了一个 single response object,其中包含 HTTP 状态代码。一个error is raised if the response is not in the 2xx range

您可以将状态代码作为 getDataFromApi() 包装函数的返回对象,但您可能需要完整的响应对象用于其他检查(如标头)。我建议完全摆脱包装。

在没有包装器的情况下,这里有 2 种使用 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;
        }
      });
  });
});