Mocha单元测试Promise引发错误

时间:2018-07-09 10:08:29

标签: node.js unit-testing mocha

我正在尝试对诺言进行单元测试。这是代码:

it('it should return some 10 user data with ok status code when called with url ', (done) => {
    return user.getUsers('https://jsonplaceholder.typicode.com/users')
    .then((response) => {
        console.log('me here')
        assert.equal(JSON.parse(response).length, 10)
    })
    .catch((err)=>{
        console.log('me in error')
        assert.fail('err')
    })
})

上面的代码在运行时会引发以下错误: Error: Timeout of 2000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (C:\Users\ajay\jay-workspace\UniTestModule\test\user.test.js)

3 个答案:

答案 0 :(得分:3)

done没有被调用,这导致测试超时。

摩卡咖啡本机支持诺言。有承诺的情况下不应使用done;相反,应返回承诺:

it('it should return some 10 user data with ok status code when called with url ', () => {
    return user.getUsers('https://jsonplaceholder.typicode.com/users')
    .then((response) => {
        console.log('me here')
        assert.equal(JSON.parse(response).length, 10)
    });
})

被拒绝的承诺将无法通过测试,也不需要assert.fail

答案 1 :(得分:1)

使用异步测试时,您应该调用done()回调(有关详细信息,请检查https://mochajs.org/#asynchronous-code)。

it('it should return some 10 user data with ok status code when called with url ', (done) => {
user.getUsers('https://jsonplaceholder.typicode.com/users')
.then((response) => {
    console.log('me here')
    assert.equal(JSON.parse(response).length, 10);
    done();
})
.catch((err)=>{
    console.log('me in error')
    assert.fail('err');
    done(err);
})

答案 2 :(得分:0)

您应该使用--timeout钩子并像./node_module/.bin/mocha test/ --timeout=5000那样增加毫秒数 或者,您可以在测试用例正文中添加this.timeout(5000)

it('it should return some 10 user data with ok status code when called with url ', (done) => {
user.getUsers('https://jsonplaceholder.typicode.com/users')
.then((response) => {
    console.log('me here')
    assert.equal(JSON.parse(response).length, 10);
    this.timeout(5000);
    setTimeout(done, 3000);
})

https://mochajs.org/#test-level