2017-10-10 117 views
0

查看其他问题,无法真正找到问题的原因。我正在尝试使用摩卡进行测试。确保在此摩卡测试中调用done()回调

it("Should not do the work",function(done) { 
    axios 
    .post("x/y",{ id:a2 }) 
    .then(function(res) { 
     assert(false,"Should not do the work"); 
     done(); 
    }) 
    .catch(function(res) { 
     assert.equal(HttpStatus.CONFLICT,res.status); 
     done(); 
    }); 
}); 

it("Should do the work",function(done) { 
    axios 
    .post("/x/y",{ id: a1 }) 
    .then(function(res) { 
     done(); 
    }) 
    .catch(done); 
}); 

结果是:

√ Should not do the work (64ms) 
1) Should do the work 
1 passing (20s) 
1 failing 

1) Error: Timeout of 20000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. 

增加超时没有工作。

+0

不要忘记你可以简单'返回'在摩卡的承诺,它会相应地处理它。在你的第一个例子中,你确定这些块实际上被执行了吗?我会检查它是否触发。 – tadman

回答

0

不要忘记你可以简单return摩卡的承诺,它会相应地处理它。在你的第一个例子中,你确定这些块实际上被执行了吗?

做一个断言可能会导致一个异常,这可能会破坏你想要做的事情。如果您的承诺库支持它,您可以始终:

it("Should not do the work",function(done) { 
axios.post("x/y",{ id:a2 }) 
    .then(function(res) { 
    assert(false,"Should not do the work"); 
    }) 
    .catch(function(res) { 
    assert.equal(HttpStatus.CONFLICT,res.status); 
    }) 
    .finally(done); 
}); 

确保无论如何都应该完成。

更妙的是:

it("Should not do the work",function() { 
    return axios.post("x/y",{ id:a2 }) 
    .then(function(res) { 
     assert(false,"Should not do the work"); 
    }) 
    .catch(function(res) { 
     assert.equal(HttpStatus.CONFLICT,res.status); 
    }) 
}); 

手表做在渔获断言和断言渔获。一个更好的计划可能是异步的:

it("Should not do the work", async function() { 
    var res = await axios.post("x/y",{ id:a2 }) 

    assert.equal(HttpStatus.CONFLICT,res.status); 
}); 
+0

第一个例子工作正常。我正面临第二个例子的问题 –

+0

也许你的实现被破坏,因为这应该工作。 – tadman

相关问题