gpt4 book ai didi

javascript - 在 Mocha 中正常工作测试所需的 setTimeout 包装

转载 作者:行者123 更新时间:2023-12-03 06:42:19 24 4
gpt4 key购买 nike

我正在为我的 Node 应用程序编写测试

'use strict';
const babelRegister = require('babel-register');
const babelPolyfill = require('babel-polyfill');
const chai = require('chai');
const sinon = require('sinon');
chai.should();
const bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const passport = require('passport');
const localStrategy = require('passport-local');

describe('test', function () {

beforeEach(function (done) {
if (mongoose.connection.readyState === 0) {
mongoose.connect('mongodb://localhost:27017/clearanceForm-test', function () {
console.log("mongodb test connection open");
done();
});
}
});

afterEach(function () {
console.log("test finished");
});

it('logs in', function (done) {
let Schema = mongoose.Schema;
let test_schema = new Schema({
username: String,
password: String,
group: {type: String, enum: ['clearance_unit_managers', 'clearance_unit_admins']}
});
let test_model = mongoose.model('test', test_schema);

(async function example() {

const unhashedPassword = Math.random().toString(36);
const passed = {
username: Math.random().toString(36),
password: bcrypt.hashSync(unhashedPassword),
group: 'clearance_unit_managers'
};

let saved = await new test_model(passed).save();
let found = await test_model.findOne({username: saved.username}).exec();
setTimeout(function () {
found.username.should.not.equal(passed.username);
done();
});

})();
});

});

在代码末尾,您可以看到我手动包装了应该在 setTimeOut 中故意失败的断言 - 否则(当我从 setTimeout 中提取断言时)我只会得到错误:超时超过 2000 毫秒。如果我在没有完成()的情况下进行测试是否通过。如果断言为真,那么一切正常......

是否断言失败是在任务队列中最后执行的,不知何故在完成()已经在堆栈中执行之后执行。

有人可以向我解释一下吗?预先感谢:)

最佳答案

您使用 async/await 的相当有创意的方式吞掉了断言抛出的异常,这导致 done() 永远不会被调用并且测试超时。

您可以使整个测试函数异步:

it('logs in', async () => {
...
let found = await test_model.findOne({username: saved.username});
found.username.should.not.equal(passed.username);
});

或者显式捕获断言异常并调用 done() 并显示错误:

try {
found.username.should.not.equal(passed.username);
done();
} catch(e) {
done(e);
}

(这很丑)

关于javascript - 在 Mocha 中正常工作测试所需的 setTimeout 包装,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37900764/

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