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
Sequelize generates setter methods with the name of the associated model. For example, the association
Review.belongsTo(User) will generate a method
Our Review 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.
How I fixed it:
Now the test will work. You'll have actual data to call your setAssociation method on.