在BeforeCreate中序列化创建第二个模型

时间:2018-10-16 14:16:03

标签: node.js ecmascript-6 async-await sequelize.js jestjs

我有一个Sequelize模型交易

var Transaction = sequelize.define('Transaction', {
    url: DataTypes.STRING,
    type: DataTypes.STRING,
    html: DataTypes.TEXT,
    brand: DataTypes.STRING,
    bookedBy: DataTypes.UUID,
    isCompliant: DataTypes.BOOLEAN,
    isConfirmedByUser: DataTypes.BOOLEAN,
    isConfirmedBySupplier: DataTypes.BOOLEAN,
    amount: DataTypes.DECIMAL,
    baseRate: DataTypes.DECIMAL,
    numberOfNights: DataTypes.DECIMAL,
    taxesAndFees: DataTypes.DECIMAL,
    total: {
        type: DataTypes.DECIMAL,
        default: 0,
    },
    searchCriterionId: DataTypes.UUID,
    queryStatId: DataTypes.UUID,
    searchCriterionId: DataTypes.UUID,
    userId: DataTypes.UUID,
    reason: DataTypes.TEXT,
    explanation: DataTypes.TEXT,
    isEdited: DataTypes.BOOLEAN,
}, {
    timestamps: true,
});

创建后,我想检查travelerId是否已关联。如果没有关联的travelerId,我想找到该旅行者记录并将其关联到交易记录。我试图在beforeCreate挂钩中做到这一点。

const assignTraveler =  async (transaction, options) => {
    if(!!transaction.travelers)
        return;

    const user = await transaction.getUser();
    transaction.setTravelers(
        [user.travelerId]
    );
};

Transaction.beforeCreate(assignTraveler);

协会看起来像这样

Transaction.associate = function(models) {
    Transaction.belongsTo(models.User, {
        foreignKey: {
            allowNull: false,
        },
    });

    Transaction.belongsTo(models.QueryStat, {
        foreignKey: {
            allowNull: true,
        },
    });

    Transaction.belongsTo(models.SearchCriterion, {
        foreignKey: {
            allowNull: true,
        },
    });

    Transaction.belongsToMany(models.Traveler, {
        through: models.BookingTraveler,
        foreignKey: 'bookingId',
        constraints: false,
    });
};

这是我正在运行的测试。

describe.only('without a Traveler', () => {
    beforeEach(async () => {
        transaction = await user.createTransaction();
        travelers = await transaction.getTravelers();
    });

    it('should use bookedBy as the Traveler', () => {
        expect(transaction.id).not.toBeNull();
        expect(travelers).not.toBeNull();
        //This line is the line that is failing
        expect(user.travelerId).toEqual(travelers[0].id);
    });
});

测试失败是间歇性的,因此我认为这与钩子中的异步事件有关。

数据库看起来正确,但是当我使用Jest测试时,关联的TravelerId返回为null。我相信这可能与mySql数据库事务有关。

0 个答案:

没有答案