gpt4 book ai didi

javascript - Mocha promise 测试超时

转载 作者:行者123 更新时间:2023-11-28 20:36:45 24 4
gpt4 key购买 nike

我在 NodeJS 中有以下测试代码:

'use strict';

// Example class to be tested
class AuthController {

constructor() {
console.log('Auth Controller test!');
}

isAuthorizedAsync(roles, neededRole) {
return new Promise((resolve, reject) => {
return resolve(roles.indexOf(neededRole) >= 0);
});
}
}

module.exports = AuthController;

和下面的 mocha 测试代码:

'use strict';

const assert = require('assert');
const AuthController = require('../../lib/controllers/auth.controller');

describe('isAuthorizedAsync', () => {
let authController = null;

beforeEach(done => {
authController = new AuthController();
done();
});

it('Should return false if not authorized', function(done) {
this.timeout(10000);

authController.isAuthorizedAsync(['user'], 'admin')
.then(isAuth => {
assert.equal(true, isAuth);
done();
})
.catch(err => {
throw(err);
done();
});
});
});

抛出以下错误:

 1 failing

1) AuthController
isAuthorizedAsync
Should return false if not authorized:
Error: Timeout of 10000ms exceeded. For async tests and hooks, ensure "done()" is called; if returning a Promise, ensure it resolves. (c:\supportal\node_modules\ttm-module\test\controllers\auth.controller.spec.js)

我尝试将默认的 mocha 测试超时增加到 10 秒,并确保 promise 得到解决。我是 Mocha 的新手。我在这里遗漏了什么吗?

最佳答案

这里的问题是您没有使用 mocha async API正确。要导致 done 回调失败,您应该在调用它时提供一个错误作为第一个参数。

如所写,您在 then 处理程序中的断言抛出,它跳过第一个 done 调用并转到 catch 处理程序。该 catch 处理程序反过来会重新抛出相同的错误,同样会阻止您到达第二个 done 回调。

你得到的是一个未处理的 promise 拒绝并且没有调用 done,导致 mocha 测试超时,可能带有关于未处理拒绝的警告消息,具体取决于你使用的 Node 版本使用。

最快的解决方法是正确使用 done 回调:

it('Should return false if not authorized', function(done) {
authController.isAuthorizedAsync(['user'], 'admin')
.then(isAuth => {
assert.equal(true, isAuth);
done();
})
.catch(err => {
done(err); // Note the difference
});
});

更简洁的解决方法是通过返回链式 promise 来使用 Mocha 的内置 promise 支持。这消除了显式处理失败案例的需要:

it('Should return false if not authorized', function() {
return authController.isAuthorizedAsync(['user'], 'admin')
.then(isAuth => {
assert.equal(true, isAuth);
});
});

关于javascript - Mocha promise 测试超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51712770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com