Debian Codegraph @

__tests__/external/shared/serializers/rest-serializer-test.js

raw
1 import { Server, Model, hasMany, belongsTo, RestSerializer } from "miragejs";
2
3 describe("External | Shared | Serializers | RestSerializer", () => {
4 let server;
5
6 afterEach(function () {
7 server.shutdown();
8 });
9
10 test("it sideloads associations and camel-cases relationships and attributes correctly for a model", () => {
11 server = new Server({
12 environment: "test",
13 models: {
14 wordSmith: Model.extend({
15 blogPosts: hasMany(),
16 }),
17 blogPost: Model.extend({
18 wordSmith: belongsTo(),
19 }),
20 },
21 serializers: {
22 application: RestSerializer,
23 wordSmith: RestSerializer.extend({
24 attrs: ["id", "name"],
25 include: ["blogPosts"],
26 }),
27 blogPost: RestSerializer.extend({
28 include: ["wordSmith"],
29 }),
30 },
31 });
32
33 let link = server.create("word-smith", { name: "Link", age: 123 });
34 link.createBlogPost({ title: "Lorem" });
35 link.createBlogPost({ title: "Ipsum" });
36
37 server.create("word-smith", { name: "Zelda", age: 230 });
38
39 let result = server.serializerOrRegistry.serialize(link);
40
41 expect(result).toEqual({
42 wordSmith: {
43 id: "1",
44 name: "Link",
45 blogPosts: ["1", "2"],
46 },
47 blogPosts: [
48 {
49 id: "1",
50 title: "Lorem",
51 wordSmith: "1",
52 },
53 {
54 id: "2",
55 title: "Ipsum",
56 wordSmith: "1",
57 },
58 ],
59 });
60 });
61
62 test("it works for has-many polymorphic associations", () => {
63 server = new Server({
64 environment: "test",
65 models: {
66 wordSmith: Model.extend({
67 posts: hasMany({ polymorphic: true }),
68 }),
69 blogPost: Model.extend(),
70 },
71 serializers: {
72 application: RestSerializer,
73 },
74 });
75
76 let post = server.create("blog-post", { title: "Post 1" });
77 let link = server.create("word-smith", {
78 name: "Link",
79 age: 123,
80 posts: [post],
81 });
82
83 let result = server.serializerOrRegistry.serialize(link);
84
85 expect(result).toEqual({
86 wordSmith: {
87 id: "1",
88 name: "Link",
89 age: 123,
90 posts: [{ id: "1", type: "blog-post" }],
91 },
92 });
93 });
94 });