90 lines
2.3 KiB
JavaScript
90 lines
2.3 KiB
JavaScript
|
|
// 测试环境配置 - 使用SQLite内存数据库进行测试
|
|||
|
|
const { Sequelize } = require('sequelize');
|
|||
|
|
|
|||
|
|
// 设置测试环境变量
|
|||
|
|
process.env.NODE_ENV = 'test';
|
|||
|
|
|
|||
|
|
// 创建测试用的SQLite内存数据库
|
|||
|
|
const testSequelize = new Sequelize('sqlite::memory:', {
|
|||
|
|
logging: false, // 关闭SQL日志
|
|||
|
|
define: {
|
|||
|
|
timestamps: true,
|
|||
|
|
underscored: false,
|
|||
|
|
freezeTableName: false
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 重写数据库配置模块,让测试使用SQLite
|
|||
|
|
const originalRequire = require;
|
|||
|
|
require = function(id) {
|
|||
|
|
if (id === '../src/config/database' || id.endsWith('/config/database')) {
|
|||
|
|
return testSequelize;
|
|||
|
|
}
|
|||
|
|
return originalRequire.apply(this, arguments);
|
|||
|
|
};
|
|||
|
|
|
|||
|
|
// 全局测试设置
|
|||
|
|
beforeAll(async () => {
|
|||
|
|
try {
|
|||
|
|
// 连接测试数据库
|
|||
|
|
await testSequelize.authenticate();
|
|||
|
|
console.log('测试数据库连接成功');
|
|||
|
|
|
|||
|
|
// 导入所有模型
|
|||
|
|
const User = require('../src/models/User');
|
|||
|
|
const Order = require('../src/models/Order');
|
|||
|
|
|
|||
|
|
// 同步数据库模型(仅在测试环境)
|
|||
|
|
await testSequelize.sync({ force: true });
|
|||
|
|
console.log('测试数据库同步完成');
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('测试数据库连接失败:', error);
|
|||
|
|
// 不要直接退出进程,让Jest处理错误
|
|||
|
|
throw error;
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 每个测试后清理数据
|
|||
|
|
afterEach(async () => {
|
|||
|
|
try {
|
|||
|
|
// 清理所有表数据,但保留表结构
|
|||
|
|
const models = Object.keys(testSequelize.models);
|
|||
|
|
for (const modelName of models) {
|
|||
|
|
await testSequelize.models[modelName].destroy({
|
|||
|
|
where: {},
|
|||
|
|
truncate: true,
|
|||
|
|
cascade: true,
|
|||
|
|
restartIdentity: true
|
|||
|
|
});
|
|||
|
|
}
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('清理测试数据失败:', error);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 测试后清理
|
|||
|
|
afterAll(async () => {
|
|||
|
|
try {
|
|||
|
|
// 关闭数据库连接
|
|||
|
|
await testSequelize.close();
|
|||
|
|
console.log('测试数据库连接已关闭');
|
|||
|
|
} catch (error) {
|
|||
|
|
console.error('测试清理失败:', error);
|
|||
|
|
}
|
|||
|
|
});
|
|||
|
|
|
|||
|
|
// 设置全局超时
|
|||
|
|
jest.setTimeout(30000);
|
|||
|
|
|
|||
|
|
// 导出测试数据库实例供测试文件使用
|
|||
|
|
global.testSequelize = testSequelize;
|
|||
|
|
|
|||
|
|
// 抑制控制台输出(可选)
|
|||
|
|
// global.console = {
|
|||
|
|
// ...console,
|
|||
|
|
// log: jest.fn(),
|
|||
|
|
// debug: jest.fn(),
|
|||
|
|
// info: jest.fn(),
|
|||
|
|
// warn: jest.fn(),
|
|||
|
|
// error: jest.fn(),
|
|||
|
|
// };
|