factory-girl
factory-girl copied to clipboard
afterCreate() in Sub-Object Creates Weird Error
We have a pretty denormalized schema, so we need to make a LOT of association calls to create a single object... When I get to the 3rd association, I get this error by simply defining afterCreate()
: TypeError: Cannot read property 'get' of undefined
in my 3rd-level factory.
Here's my example:
// STEP 1: create a customer record
factory.define('customer', models.Customer, {
company_id: factory.assoc('company', 'id'), // NOTE: this code is skipped because it works fine
}, {
async afterCreate (model, attrs, buildOptions) {
// attempting to create a user record for the customer
const user = await factory.create('user', { customer_id: model.id })
console.info('user:', user)
},
},
)
// STEP 2: create a user record
factory.define('user', models.User, {
contact_id: factory.assoc('contact', 'id'), // create a contact
username: factory.sequence('User.username', (n) => `Username${n}`),
})
// STEP 3: create a contact record
factory.define('contact', models.Contact, {
title: 'Sir',
first_name: factory.sequence('Contact.first_name', (n) => `FirstName{n}`),
last_name: factory.sequence('Contact.last_name', (n) => `LastName{n}`),
notes: 'No thanks',
avatar: 'www.avatar.com/something.jpeg',
}, {
// defining this function causes the error
async afterCreate (model, attrs, buildOptions) {
// TODO: define even more sub-models...
return Promise.resolve()
},
},
)
We're using Sequelize
as our ORM as well. I tried Googling for answers, but couldn't find any solutions.
for some reasons in case when factory-girl build schema doesn't match DB-schema, FG doesn't throw error. It just returns undefined. So guys who still uses this project : make sure your build schema fits to DB schema.