Skip to content

Commit

Permalink
test: add tests for 'FindOrCreate'
Browse files Browse the repository at this point in the history
  • Loading branch information
sonirico committed Jun 4, 2020
1 parent 1de0414 commit 9a94f4c
Showing 1 changed file with 83 additions and 3 deletions.
86 changes: 83 additions & 3 deletions types/test/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,86 @@ UserModel.findCreateFind({
}
})

/**
* Tests for findCreateOrCreate() type.
*/
class FindOrCreateModelTest extends Model {
static async testRowIsReturnedWhenAlreadyExists() {
let [model, created] = await this.findOrCreate({
fields: [ 'beta_user', 'username' ],
where: {
username: "test.user",
},
defaults: {
username: "test.user"
}
})

if (! created) {
throw new Error('model should have been created');
}

[model, created] = await this.findOrCreate({
fields: [ 'beta_user', 'username' ],
where: {
username: "test.user",
},
defaults: {
username: "test.user"
}
})

if (created) {
throw new Error(`'findOrCreate' should have returned already existing model`);
}
}

static async testFieldNotPresentInFieldsIsIgnored() {
const [model, created] = await this.findOrCreate({
fields: [ 'beta_user' ],
where: {
username: "john.doe",
},
defaults: {
username: "john.done"
}
})

if (! created) {
throw new Error('model should have been created');
}

const rawModel = model.toJSON() as { username: string };
if (rawModel.username === 'john.doe') {
throw new Error("'findOrCreate' should have ignored 'username' attribute");
}
}

static async testFieldPresentInFieldsIsSet() {
const [model, created] = await this.findOrCreate({
fields: [ 'username' ],
where: {
username: "jane.doe"
},
defaults: {
username: "jane.doe",
}
})

if (! created) {
throw new Error('model should have been created');
}

const rawModel = model.toJSON() as { username: string };
if (rawModel.username !== 'jane.doe') {
throw new Error("'findOrCreate' should have been set 'username' attribute");
}
}
}

FindOrCreateModelTest.testRowIsReturnedWhenAlreadyExists();
FindOrCreateModelTest.testFieldNotPresentInFieldsIsIgnored();
FindOrCreateModelTest.testFieldPresentInFieldsIsSet();
/**
* Test for primaryKeyAttributes.
*/
Expand All @@ -116,12 +196,12 @@ someInstance.getOthers({
joinTableAttributes: { include: [ 'id' ] }
})

/**
/**
* Test for through options in creating a BelongsToMany association
*/
class Film extends Model {}

class Actor extends Model {}
class Actor extends Model {}

Film.belongsToMany(Actor, {
through: {
Expand All @@ -135,4 +215,4 @@ Actor.belongsToMany(Film, {
model: 'FilmActors',
paranoid: true
}
})
})

0 comments on commit 9a94f4c

Please sign in to comment.