提问者:小点点

sequelize index选项运行两次并导致测试失败


下面是我的模型:


var PaymentsToMonths = db.define('PaymentsToMonths', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true
    },
    PaymentPlanDetailID: {
        type: Sequelize.DECIMAL,
        allowNull: false,
    },
    month: {
        type: Sequelize.DECIMAL,
        allowNull: false,
        // todo add validation 1-12
    },
    year: {
        type: Sequelize.DECIMAL,
        allowNull: false,
    },
    sum: {
        type: Sequelize.DECIMAL,
        allowNull: false,
    },
    monthTotal: {
        type: Sequelize.DECIMAL,
        allowNull: false,
    }
    
}, {
    tableName: 'PaymentsToMonths',
    freezeTableName: true, // Model tableName will be the same as the model name
    timestamps: true,
    indexes: [
        {
            unique: true,
            fields: ['PaymentPlanDetailID', 'month', 'year'],
            name: 'unique_payment_per_month_and_year'
        }
    ]
})

运行测试时,我看到以下错误:

  console.error
    SequelizeDatabaseError: Duplicate key name 'unique_payment_per_month_and_year'

这是因为运行了两个相同的行:

  console.log
    Executing (default): ALTER TABLE `PaymentsToMonths` ADD UNIQUE INDEX `unique_payment_per_month_and_year` (`PaymentPlanDetailID`, `month`, `year`)

      at Sequelize.log (../node_modules/sequelize/lib/sequelize.js:1171:15)

  console.log
    Executing (default): ALTER TABLE `PaymentsToMonths` ADD UNIQUE INDEX `unique_payment_per_month_and_year` (`PaymentPlanDetailID`, `month`, `year`)

为什么会出现这种情况?

不确定是否相关,但我也有用于测试的代码:

afterAll(async (done) => {
    jest.restoreAllMocks();

    // remove all data and tables
    await sequelize.drop();

    // to end the jest process
    done();

})

共1个答案

匿名用户

结果是因为使用了

sequelize.sync({force: false})

在我的main_test.js文件中。

愚蠢的错误。

移除其中一个管用。