JEST中的负API测试

问题描述 投票:0回答:1

当我提供有效的凭据时,它会通过。但是我想用无效的凭据开玩笑地测试我的登录API,并期望状态码为401。如何做到这一点?


  it('fails with invalid credentials', async () => {
  const  res = await axios.post('/rest/api/login', data);
    console.log('Status:', response.status);
    expect(response.status).toBe(401);
  });

获取以下错误消息

Request failed with status code 401

      at createError (node_modules/axios/lib/core/createError.js:16:15)
      at settle (node_modules/axios/lib/core/settle.js:18:12)
      at IncomingMessage.handleStreamEnd (node_modules/axios/lib/adapters/http.js:191:11)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        4.285 s
node.js jest
1个回答
0
投票

只需尝试:

expect(() => await axios.post('/rest/api/login', data)).toThrow('Request failed with status code 401');

 try {
      await axios.post('/rest/api/login', data);
      expect(true).toBe(false);
  } catch (e) {
      expect(e.message).toBe("Request failed with status code 401");
  }
© www.soinside.com 2019 - 2024. All rights reserved.