Debian Codegraph @

__tests__/external/shared/serializers/json-api-serializer/attrs-test.js

raw
1 import { Server, Model, JSONAPISerializer } from "miragejs";
2
3 describe("External | Shared | Serializers | JSON API Serializer | Attrs List", () => {
4 let server;
5
6 beforeEach(() => {
7 server = new Server({
8 models: {
9 wordSmith: Model,
10 photograph: Model,
11 },
12 });
13 });
14
15 afterEach(() => {
16 server.shutdown();
17 });
18
19 test(`it returns only the whitelisted attrs when serializing a model`, () => {
20 server.config({
21 serializers: {
22 application: JSONAPISerializer,
23 wordSmith: JSONAPISerializer.extend({
24 attrs: ["firstName"],
25 }),
26 },
27 });
28 let user = server.schema.wordSmiths.create({
29 id: 1,
30 firstName: "Link",
31 age: 123,
32 });
33
34 let result = server.serializerOrRegistry.serialize(user);
35
36 expect(result).toEqual({
37 data: {
38 type: "word-smiths",
39 id: "1",
40 attributes: {
41 "first-name": "Link",
42 },
43 },
44 });
45 });
46
47 test(`it returns only the whitelisted attrs when serializing a collection`, () => {
48 server.config({
49 serializers: {
50 application: JSONAPISerializer,
51 wordSmith: JSONAPISerializer.extend({
52 attrs: ["firstName"],
53 }),
54 },
55 });
56 server.schema.wordSmiths.create({ id: 1, firstName: "Link", age: 123 });
57 server.schema.wordSmiths.create({ id: 2, firstName: "Zelda", age: 456 });
58
59 let collection = server.schema.wordSmiths.all();
60 let result = server.serializerOrRegistry.serialize(collection);
61
62 expect(result).toEqual({
63 data: [
64 {
65 type: "word-smiths",
66 id: "1",
67 attributes: {
68 "first-name": "Link",
69 },
70 },
71 {
72 type: "word-smiths",
73 id: "2",
74 attributes: {
75 "first-name": "Zelda",
76 },
77 },
78 ],
79 });
80 });
81
82 test(`it can use different attr whitelists for different serializers`, () => {
83 server.config({
84 serializers: {
85 wordSmith: JSONAPISerializer.extend({
86 attrs: ["firstName"],
87 }),
88 photograph: JSONAPISerializer.extend({
89 attrs: ["title"],
90 }),
91 },
92 });
93
94 let link = server.schema.wordSmiths.create({
95 id: 1,
96 firstName: "Link",
97 age: 123,
98 });
99 expect(server.serializerOrRegistry.serialize(link)).toEqual({
100 data: {
101 type: "word-smiths",
102 id: "1",
103 attributes: {
104 "first-name": "Link",
105 },
106 },
107 });
108
109 let photo = server.schema.photographs.create({
110 id: 1,
111 title: "Lorem ipsum",
112 createdAt: "2010-01-01",
113 });
114 expect(server.serializerOrRegistry.serialize(photo)).toEqual({
115 data: {
116 type: "photographs",
117 id: "1",
118 attributes: {
119 title: "Lorem ipsum",
120 },
121 },
122 });
123 });
124 });