Debian Codegraph @

__tests__/external/shared/serializers/base/associations/sideloading-and-embedded-model-test.js

raw
1 import { Server, Model, hasMany, belongsTo, Serializer } from "miragejs";
2
3 describe("External | Shared | Serializers | Base | Associations | Sideloading and Embedded Models", function () {
4 let server, BaseSerializer;
5
6 beforeEach(function () {
7 BaseSerializer = Serializer.extend({
8 embed: false,
9 });
10
11 server = new Server({
12 models: {
13 wordSmith: Model.extend({
14 posts: hasMany("blog-post"),
15 }),
16 blogPost: Model.extend({
17 author: belongsTo("word-smith"),
18 comments: hasMany("fine-comment"),
19 }),
20 fineComment: Model.extend({
21 post: belongsTo("blog-post"),
22 }),
23 },
24 });
25
26 let wordSmith = server.schema.wordSmiths.create({ name: "Link" });
27 let blogPost = wordSmith.createPost({ title: "Lorem" });
28 blogPost.createComment({ text: "pwned" });
29
30 wordSmith.createPost({ title: "Ipsum" });
31
32 server.schema.wordSmiths.create({ name: "Zelda" });
33 });
34
35 afterEach(function () {
36 server.shutdown();
37 });
38
39 test(`it can sideload a model with a has-many relationship containing embedded models`, () => {
40 server.config({
41 serializers: {
42 application: BaseSerializer,
43 wordSmith: BaseSerializer.extend({
44 embed: false,
45 include: ["posts"],
46 }),
47 blogPost: BaseSerializer.extend({
48 embed: true,
49 include: ["comments"],
50 }),
51 },
52 });
53
54 let link = server.schema.wordSmiths.find(1);
55 let result = server.serializerOrRegistry.serialize(link);
56
57 expect(result).toEqual({
58 wordSmith: {
59 id: "1",
60 name: "Link",
61 postIds: ["1", "2"],
62 },
63 blogPosts: [
64 { id: "1", title: "Lorem", comments: [{ id: "1", text: "pwned" }] },
65 { id: "2", title: "Ipsum", comments: [] },
66 ],
67 });
68 });
69
70 test(`it can sideload a model with a belongs-to relationship containing embedded models`, () => {
71 server.config({
72 serializers: {
73 application: BaseSerializer,
74 fineComment: BaseSerializer.extend({
75 embed: false,
76 include: ["post"],
77 }),
78 blogPost: BaseSerializer.extend({
79 embed: true,
80 include: ["author"],
81 }),
82 },
83 });
84
85 let fineComment = server.schema.fineComments.find(1);
86 let result = server.serializerOrRegistry.serialize(fineComment);
87
88 expect(result).toEqual({
89 fineComment: { id: "1", text: "pwned", postId: "1" },
90 blogPosts: [
91 {
92 id: "1",
93 title: "Lorem",
94 author: { id: "1", name: "Link" },
95 },
96 ],
97 });
98 });
99 });