我正在用Jest编写HTTP测试。我故意向/order
端点发送格式错误的请求。像这样:
const axios = require('axios');
describe('a request to the API POST /order', () => {
test('with a correct body', () => {
axios.post("http://localhost:3000/order", {})
.catch(function (error) {
expect(1+4).toBe(3);
});
});
});
捕获了错误,但是expect(1+4).toBe(3)
并未使测试失败。无论如何,如果我将该块移动到catch
语句之外,则它将成功失败。我该如何解决?
答案 0 :(得分:0)
axios.post
返回一个promise,表示您正在测试异步代码。从这个docs
Jest需要知道要测试的代码何时完成,然后才能继续进行另一个测试。笑话有几种处理方法。
const axios = require('axios');
describe('a request to the API POST /order', () => {
test('with a correct body - 1', () => {
return axios.post('http://localhost:3000/order', {}).catch(function(error) {
expect(1 + 4).toBe(3);
});
});
test('with a correct body - 2', done => {
axios.post('http://localhost:3000/order', {}).catch(function(error) {
expect(1 + 4).toBe(3);
done();
});
});
});
现在,开玩笑会让您的测试失败。
FAIL src/stackoverflow/58828255/index.spec.ts (6.965s)
a request to the API POST /order
✕ with a correct body - 1 (40ms)
✕ with a correct body - 2 (8ms)
● a request to the API POST /order › with a correct body - 1
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: 5
6 | test('with a correct body - 1', () => {
7 | return axios.post('http://localhost:3000/order', {}).catch(function(error) {
> 8 | expect(1 + 4).toBe(3);
| ^
9 | });
10 | });
11 |
at src/stackoverflow/58828255/index.spec.ts:8:21
● a request to the API POST /order › with a correct body - 2
expect(received).toBe(expected) // Object.is equality
Expected: 3
Received: 5
12 | test('with a correct body - 2', done => {
13 | axios.post('http://localhost:3000/order', {}).catch(function(error) {
> 14 | expect(1 + 4).toBe(3);
| ^
15 | done();
16 | });
17 | });
at src/stackoverflow/58828255/index.spec.ts:14:21
Test Suites: 1 failed, 1 total
Tests: 2 failed, 2 total
Snapshots: 0 total
Time: 7.974s