[当使用mocha测试异步功能的结果时,await
之后的测试会弹出嵌套结构,就像下面的前两个测试一样:
✓ email
✓ phone
current unit
fetch data
✓ is 5==5
3 passing (10ms)
我们如何使测试出现在适当的位置?
代码:
const chai = require('chai');
chai.should();
describe ("current unit", async () => {
describe ("fetch data", async () => {
it ("is 5==5", () => { chai.expect(5).to.equal(5); });
const UserData = await getUserData("UserName");
it ("email", () => { UserData.email.should.equal("[email protected]"); });
it ("phone", () => { UserData.phone.should.equal("+1 (800) 123 4567"); });
});
});
function getUserData(param) { return new Promise(resolve => setTimeout(() => resolve({ email:"[email protected]",phone:"+1 (800) 123 4567" }), 1/*ms*/));}
done()
函数。这是一个例子:it ("email", (done) => {
UserData.email.should.equal("[email protected]");
done();
});