gpt4 book ai didi

javascript - sequelize.sync({ 强制 : true }) sometimes fails to set up database correctly

转载 作者:行者123 更新时间:2023-11-29 11:00:33 35 4
gpt4 key购买 nike

我正在尝试使用 Sequelize 和 PostgreSQL 设置测试夹具。然而,我写的测试有时会通过,有时会失败。错误范围从 SequelizeDatabaseError: type "participants_id_seq"already existsSequelizeUniqueConstraintError: Validation errorSequelizeDatabaseError: relation "participants"does not exist,这让我相信要么我错误地设置了等待,要么我错误地设置了同步。我试过使用 async/await,我也试过使用回调设置 Promises,但没有成功。

在每次测试之前,我调用sync({ force: true }),就像这样

const { sequelize, participants: Participants } = require('../../models');

const existingUserCredentials = {
teamName: 'TeamName',
firstName: 'FirstName',
lastName: 'LastName',
email: 'helloworld@helloworld.com',
password: 'helloworld',
};

const Fixture = async () => {
try {
await sequelize.sync({ force: true });
await Participants.create(existingUserCredentials);
} catch (err) {
logger.error(err);
throw err;
}
};

module.exports = {
Fixture
};

然后我在我的测试用例中这样调用它:

describe('POST /login', () => {
beforeEach(async () => {
await Fixture();
});

it('throws unauthorized when user does not exist', async () => {
const { body, status } = await request(app)
.post('/api/login')
.send({
email: 'someemail@helloworld.com',
password: 'hunter123',
});

expect(body).toEqual({
message: messages.INVALID_LOGIN_CREDENTIALS,
});
expect(status).toEqual(HttpStatus.UNAUTHORIZED);
});
});

此测试有时会通过,但有时会失败并出现不同的错误。

我的模型是这样的:

const bcrypt = require('bcryptjs');

module.exports = (sequelize, DataTypes) => {
const Participant = sequelize.define('participants', {
teamName: {
type: DataTypes.STRING,
allowNull: true,
},
firstName: {
type: DataTypes.STRING,
allowNull: false,
},
lastName: {
type: DataTypes.STRING,
allowNull: false,
},
email: {
type: DataTypes.STRING,
allowNull: false,
},
password: {
type: DataTypes.STRING,
allowNull: false,
set(password) {
const hash = bcrypt.hashSync(password, bcrypt.genSaltSync(10));
this.setDataValue('password', hash);
},
},
});

Participant.verifyPassword = (password, hash) =>
bcrypt.compareSync(password, hash);

return Participant;
};

我的迁移看起来像这样

module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.createTable('participants', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER,
},
teamName: {
type: Sequelize.STRING,
allowNull: true,
},
firstName: {
type: Sequelize.STRING,
allowNull: false,
},
lastName: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
},
password: {
type: Sequelize.STRING,
allowNull: false,
},
createdAt: {
allowNull: false,
type: 'TIMESTAMP',
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
},
updatedAt: {
allowNull: false,
type: 'TIMESTAMP',
defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'),
},
}),
down: (queryInterface) => queryInterface.dropTable('participants'),
};

我是否正确设置了它以便我可以为每个测试提供一个干净的数据库?感谢您的帮助!

最佳答案

更新

我想通了。原来 Jest 并行运行测试用例,所以测试数据库被多个测试用例同时使用。真正的解决方案是通过将 --runInBand 标志添加到测试命令来顺序运行测试用例

// package.json
{
...
"scripts": {
...
"test": "cross-env NODE_ENV=test jest --runInBand"
}
...
}

但是,这会减慢运行测试用例所需的时间。更好的解决方案可能是模拟您的数据库,而不是使用实际的测试数据库。那里有一些,例如 sequelize-mocksequelize-mocking .


所以,我无法用 PostgreSQL 解决这个问题。相反,我将我的 Sequelize 配置切换为使用 SQLite 进行测试并且它有效。这是我的配置

module.exports = {
development: {
username: process.env.PGUSER,
password: process.env.PGPASSWORD,
database: process.env.PGDATABASE,
host: process.env.PGHOST || '127.0.0.1',
dialect: 'postgres',
operatorsAliases: false,
},
test: {
username: process.env.SQLITEUSER,
password: process.env.SQLITEPASSWORD,
database: process.env.SQLITEDATABASE,
host: process.env.PGHOST || '127.0.0.1',
dialect: 'sqlite',
operatorsAliases: false,
},
production: {
username: process.env.PGUSER,
password: process.env.PGPASSWORD,
database: process.env.PGPRODDATABASE,
host: process.env.PGHOST || '127.0.0.1',
dialect: 'postgres',
operatorsAliases: false,
logging: false,
},
};

虽然我不认为这是一个很好的解决方案,但我打算让这个问题悬而未决

关于javascript - sequelize.sync({ 强制 : true }) sometimes fails to set up database correctly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47834131/

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