Mysterious Errors — SequelizeBaseError: Insert or Update on Table Violates Foreign Key Constraints

Sequelize is a great library, but its documentation leaves a lot to be desired.

Recently, while writing unit tests for an e-commerce site project, I came across this cryptic error:

SequelizeBaseError: insert or update on table “reviews” violates foreign key constraint “reviews_user_id_fkey”

From the error, it’s not too clear what has gone wrong.

The model I was testing had two associations, using Sequelize’s belongsTo method.

Sequelize generates setter methods with the name of the associated model.

For example, the association Review.belongsTo(User) will generate a method setUser().

Our Review model would now have an integer id of the associated model.

I assumed that I could fake associations by calling review.setUser() with an integer directly, even though no model in the database had that id. Nope!

Here’s the problematic test:

It turns out that to call the setAssociation method, you’ll need to create actual records in your database. To set the association, you need a model to associate.

How I fixed it:

These will run before every test, making sure data is available for your test. Now the test will work.

Hope this saves you some debugging time!

Originally published at