Async Best Practise2019-06-30 13:03Dev, JavaScript, Jest

Jest Async Best Practise

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

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

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

Use beforeAll() instead

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 来处理

  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;
  });
Powered by Remix
|
Designed by szhshp
|
Copyright © szhshp 2022