Node.js 在运行Jest测试之前,请等待数据库初始化
我必须向几个月前使用NodeJS开发的API后端添加一些特性及其相应的测试。在检查我当时编写的测试用例时,我遇到了以下代码: 索引路由.spec.jsNode.js 在运行Jest测试之前,请等待数据库初始化,node.js,jestjs,sequelize.js,Node.js,Jestjs,Sequelize.js,我必须向几个月前使用NodeJS开发的API后端添加一些特性及其相应的测试。在检查我当时编写的测试用例时,我遇到了以下代码: 索引路由.spec.js const app = require('../../app'); const request = require('supertest'); function delay() { return new Promise((resolve, reject) => { setTimeout(() => { re
const app = require('../../app');
const request = require('supertest');
function delay() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 3000);
});
}
beforeAll(async () => {
await delay();
});
// START TESTS
async function run() {
try {
// Creates database if it doesn't exist
await DB_init();
// Test database connection
await DB_test();
// Connection was OK, sync tables and relationships
await DB_sync();
// Check if the DB is empty and, in this case, fill the basic data
await DB_init_values();
} catch(error => {
log.error("Couldn't connect to the database '"+dbName+"':", error);
process.exit(1);
}
}
// Init the DB
run();
延迟的原因是给应用程序时间初始化数据库连接(我使用Sequelize ORM)。这是在应用程序主文件(app.js
)所需的文件(db.js
)中完成的:
db.js
const app = require('../../app');
const request = require('supertest');
function delay() {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve();
}, 3000);
});
}
beforeAll(async () => {
await delay();
});
// START TESTS
async function run() {
try {
// Creates database if it doesn't exist
await DB_init();
// Test database connection
await DB_test();
// Connection was OK, sync tables and relationships
await DB_sync();
// Check if the DB is empty and, in this case, fill the basic data
await DB_init_values();
} catch(error => {
log.error("Couldn't connect to the database '"+dbName+"':", error);
process.exit(1);
}
}
// Init the DB
run();
这是可行的,但现在我必须添加更多的测试,我想重构这段代码,以避免添加人为延迟。在开始测试之前,如何等待数据库初始化代码完成?似乎不可能同步地要求模块,是吗
干杯,请点击此处查看: