要重构ExpressJS + Sequelize文件以便正确使用Jest,你可以采取以下步骤:
// models/index.js
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const config = require('../config/database.js');
const sequelize = new Sequelize(config.database, config.username, config.password, config);
const models = {};
fs.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== 'index.js'))
.forEach(file => {
const model = sequelize.import(path.join(__dirname, file));
models[model.name] = model;
});
Object.keys(models).forEach(modelName => {
if (models[modelName].associate) {
models[modelName].associate(models);
}
});
module.exports = {
sequelize,
models,
};
// models/user.js
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
name: DataTypes.STRING,
email: DataTypes.STRING,
password: DataTypes.STRING,
}, {});
User.associate = function(models) {
User.hasMany(models.Post);
};
return User;
};
// config/database.js
module.exports = {
database: 'your_database_name',
username: 'your_database_username',
password: 'your_database_password',
host: 'your_database_host',
dialect: 'your_database_dialect',
};
// __tests__/routes/users.test.js
const request = require('supertest');
const app = require('../app');
describe('GET /users', () => {
it('should return a list of users', async () => {
const response = await request(app).get('/users');
expect(response.statusCode).toBe(200);
expect(response.body).toHaveLength(2);
});
});
在重构后的项目结构中,你可以更方便地编写Jest测试,并且能够更好地隔离测试和生产代码。当你运行Jest测试时,它将模拟HTTP请求并执行数据库操作,以便测试你的ExpressJS应用和Sequelize模型的正确性。
腾讯云相关产品推荐链接地址:
领取专属 10元无门槛券
手把手带您无忧上云