Async Best Practise
文章目录

Jest Async Best Practise

关键字: Jest with multiple async, Jest nested async

切记这个地方不要使用嵌套的 test, 使用 beforeAll()

** DO NOT USE nested test** !!!

Use beforeAll() instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
describe('Delete User', () => {
let xid;

// 有时候我们先要从数据库提取一些预备数据
beforeAll(() => {
axios.get(`${domain}graphQL?query={
getUser(username: "${testAccount.username}", password: "123456789") {
errors
success
_id
}
}
`)
.then(res => res.data.data.getUser)
.then((res) => {
xid = res._id; // 将其设置给局部变量, 随后下方就可以使用这个变量了
});
});


test('Get User: Wrong ID', () => axios.post(`${domain}graphQL`, {
query: `mutation{
deleteUser(_id: "5d0ef90a36ae0b798cd11111") { # wrong id here
errors
success
}
}`,
})
.then(res => res.data.data.deleteUser)
.then((res) => {
expect(res.success).toEqual(false);
expect(res.errors).toEqual([ERRORS.USER.USER_NOT_FOUND]);
}));

test('Get User: Correct Inputs', () => axios.post(`${domain}graphQL`, {
query: `mutation{
deleteUser(_id: "${xid}") {
errors
success
}
}`,
})
.then(res => res.data.data.deleteUser)
.then((res) => {
expect(res.success).toEqual(true);
expect(res.errors).toEqual([]);
}));
});

上方也可以使用 Async/Await 来处理

1
2
3
4
5
6
7
8
9
10
11
12
let item_id;

beforeAll(async () => {
const res = await axios.post(`${domain}graphQL`, {
query: `mutation{
addItem(itemname: "${testItem2.itemname}", itemid: "${testItem2.itemid}", itemtype: "Material") {
_id
}
}`,
});
item_id = res.data.data.addItem._id;
});