我正在尝试对一个预验证的mongoose模型方法进行单元测试。
这是模型部分:
export const hashPassword = async function () {
console.log('test1');
return Promise.resolve();
};
userSchema.pre('validate', hashPassword);
这是单元测试部件
it('hash password pre save hook', async () => {
const user = new User({
email: 'email@email.com',
firstName: 'firstName',
lastName: 'lastName',
userName: 'userName',
password: 'password',
});
await user.validate();
console.log('test2');
});
最后,错误信息我有
错误:超过了2000ms的超时时间。对于异步测试和挂钩,请确保"done((";被称为;如果返回Promise,请确保它已解决。
因此方法中的console.log被触发,而不是第二个。我把代码简化为最简单的逻辑,但仍然无法使其工作。
我检查了一下,结果是100%阳性,它来自钩子本身。不是来自摩卡,也不是来自哈希函数,而是来自猫鼬钩子。
PS:是的,我试图增加超时时间,但没有成功
由于您的测试包括异步代码,因此在使用测试进行验证之前,您需要确保代码完成其功能。
从Mocha文档,测试异步代码:
通过将一个参数(通常命名为done(添加到测试回调的it((中,Mocha将知道它应该等待调用该函数来完成测试。此回调接受Error实例(或其子类(或falsy值;其他任何东西都是无效的用法,并引发错误(通常导致测试失败(。
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(function(err) {
if (err) done(err);
else done();
});
});
});
});
或者,直接使用done((回调(如果存在,它将处理错误参数(:
describe('User', function() {
describe('#save()', function() {
it('should save without error', function(done) {
var user = new User('Luna');
user.save(done);
});
});
});
此外,如果从未调用done()
,测试将失败(超时错误(
要了解更多信息,请访问:https://mochajs.org/#asynchronous-代码
好吧,睡了一觉之后,我找到了这个问题的原因。我在模式中有一个异步验证器,它执行对数据库的请求。我没有踩它,所以,它触发了暂停。
以下是负责的部件代码:
const userSchema = new Schema({
email: {
type: String,
required: true,
unique: true,
validate: {
async validator(email): Promise<boolean> {
const isNonUniqueEmail = await mongoose.model('user').exists({ email });
return !isNonUniqueEmail;
},
message: 'nonUniqEmail',
},
},
});
我忘记了第一条堆栈溢出规则:在上网询问之前先睡一觉。