gpt4 book ai didi

javascript - 为 mocha 测试设置数据库连接的最佳实践和最有效的方法

转载 作者:搜寻专家 更新时间:2023-10-30 20:34:33 24 4
gpt4 key购买 nike

我有一组在我的代码上运行的测试。在测试运行之前,我想打开一个到测试数据库的数据库连接,并确保数据库是空的。此连接将对所有测试保持打开状态。然后,当所有测试完成后,关闭数据库连接并清空数据库。

我目前的解决方案涉及为每个文件打开一个连接,这将导致整体连接量很大。最好打开一次连接 --> 运行测试 --> 清除数据库 --> 关闭一次连接。

这是我的一个 mocha 测试文件的代码:

import {assert} from 'chai';
import mongoose from 'mongoose';
import User from '../../../server/models/user.js';
import 'dotenv/config';

mongoose.connect(process.env.DB_TEST).then(db => {
describe('User Model', function() {
it('Save', function(done) {
var john = new User({
name: {
first: 'John',
last: 'smith'
},
email: 'john.smith@gmail.com',
type: 'student'
});

john.save(done);
});
});
}).catch(err => {
console.log('Failed to connect to testing database: ' + err);
});

目前,这段代码是完全可用的。但是,我确信有更好的方法来处理打开、清除和关闭我的测试集合的数据库连接。

最佳答案

您可以使用我所说的根级钩子(Hook)

示例:

测试文件

test0.es6
test1.es6
test2.es6
...

使用test0.es6文件来处理数据库连接,如:

// ROOT HOOK Executed before the test run
before((done) => {
connectToDatabase()
.then(() => {
...
done();
})
.catch(...);
});

// ROOT HOOK Excuted after every tests finished
after((done) => {
disconnectFromDatabase()
.then(() => {
...
done();
})
.catch(...);
});

使用其他文件通过数据库连接执行测试:

/** @test {core} */
describe('core', () => {
/** @test {core#executeCommandApi} */
describe('executeCommandApi()', () => {
it(...);
});
});

须知:Mocha 按字母顺序调用文件

关于javascript - 为 mocha 测试设置数据库连接的最佳实践和最有效的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47450779/

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