| 1 |
import Helper from "./_helper"; |
| 2 |
import { Model } from "miragejs"; |
| 3 |
|
| 4 |
describe("External | Shared | ORM | Mixed | Many To One | create", () => { |
| 5 |
let helper; |
| 6 |
beforeEach(() => { |
| 7 |
helper = new Helper(); |
| 8 |
helper.schema.registerModel("foo", Model); |
| 9 |
}); |
| 10 |
afterEach(() => { |
| 11 |
helper.shutdown(); |
| 12 |
}); |
| 13 |
|
| 14 |
test("it sets up associations correctly when passing in the foreign key", () => { |
| 15 |
let { schema } = helper; |
| 16 |
let user = schema.create("user"); |
| 17 |
let post = schema.create("post", { |
| 18 |
userId: user.id, |
| 19 |
}); |
| 20 |
user.reload(); |
| 21 |
|
| 22 |
expect(post.user.attrs).toEqual(user.attrs); |
| 23 |
expect(post.userId).toEqual(user.id); |
| 24 |
expect(user.posts.includes(post)).toBeTruthy(); |
| 25 |
expect(user.postIds).toEqual([post.id]); |
| 26 |
|
| 27 |
let { db } = helper; |
| 28 |
expect(db.posts).toHaveLength(1); |
| 29 |
expect(db.posts[0]).toEqual({ id: "1", userId: "1" }); |
| 30 |
expect(db.users).toHaveLength(1); |
| 31 |
expect(db.users[0]).toEqual({ id: "1", postIds: ["1"] }); |
| 32 |
}); |
| 33 |
|
| 34 |
test("it sets up associations correctly when passing in the association itself", () => { |
| 35 |
let { schema } = helper; |
| 36 |
let user = schema.create("user"); |
| 37 |
let post = schema.create("post", { |
| 38 |
user, |
| 39 |
}); |
| 40 |
|
| 41 |
expect(post.user.attrs).toEqual(user.attrs); |
| 42 |
expect(post.userId).toEqual(user.id); |
| 43 |
expect(user.posts.includes(post)).toBeTruthy(); |
| 44 |
expect(user.postIds).toEqual([post.id]); |
| 45 |
|
| 46 |
let { db } = helper; |
| 47 |
expect(db.posts).toHaveLength(1); |
| 48 |
expect(db.posts[0]).toEqual({ id: "1", userId: "1" }); |
| 49 |
expect(db.users).toHaveLength(1); |
| 50 |
expect(db.users[0]).toEqual({ id: "1", postIds: ["1"] }); |
| 51 |
}); |
| 52 |
|
| 53 |
test("it throws an error if a model is passed in without a defined relationship", () => { |
| 54 |
let { schema } = helper; |
| 55 |
|
| 56 |
expect(function () { |
| 57 |
schema.create("post", { |
| 58 |
foo: schema.create("foo"), |
| 59 |
}); |
| 60 |
}).toThrow(); |
| 61 |
}); |
| 62 |
|
| 63 |
test("it throws an error if a collection is passed in without a defined relationship", () => { |
| 64 |
let { schema } = helper; |
| 65 |
schema.create("foo"); |
| 66 |
schema.create("foo"); |
| 67 |
|
| 68 |
expect(function () { |
| 69 |
schema.create("post", { |
| 70 |
foos: schema.foos.all(), |
| 71 |
}); |
| 72 |
}).toThrow(); |
| 73 |
}); |
| 74 |
}); |