Debian Codegraph @

__tests__/external/shared/serializers/base/override-serialize-test.js

raw
1 import { Server, Model, Serializer } from "miragejs";
2
3 describe("External | Shared | Serializers | Base | Overriding Serialize", function () {
4 let server;
5
6 beforeEach(function () {
7 server = new Server({
8 models: {
9 wordSmith: Model,
10 },
11 });
12 });
13
14 afterEach(function () {
15 server.shutdown();
16 });
17
18 test(`it can use a completely custom serialize function`, () => {
19 server.config({
20 serializers: {
21 wordSmith: Serializer.extend({
22 serialize() {
23 return "blah";
24 },
25 }),
26 },
27 });
28 let wordSmith = server.schema.wordSmiths.create({
29 id: 1,
30 title: "Link",
31 });
32
33 let result = server.serializerOrRegistry.serialize(wordSmith);
34
35 expect(result).toEqual("blah");
36 });
37
38 test(`it can access the request in a custom serialize function`, () => {
39 server.config({
40 serializers: {
41 wordSmith: Serializer.extend({
42 serialize(response, request) {
43 return request.queryParams.foo || "blah";
44 },
45 }),
46 },
47 });
48
49 let wordSmith = server.schema.wordSmiths.create({
50 id: 1,
51 title: "Link",
52 });
53
54 let request = {
55 url: "/word-smiths/1?foo=bar",
56 params: { id: "1" },
57 queryParams: { foo: "bar" },
58 };
59 let result = server.serializerOrRegistry.serialize(wordSmith, request);
60
61 expect(result).toEqual("bar");
62 });
63
64 test(`it can access the databse while in a serializer method`, () => {
65 server.config({
66 serializers: {
67 wordSmith: Serializer.extend({
68 serialize(response, request) {
69 let id = request.params.id;
70 return server.schema.db.wordSmiths.find(id).title || "No title";
71 },
72 }),
73 },
74 });
75
76 let wordSmith = server.schema.wordSmiths.create({
77 id: 1,
78 title: "Title in database",
79 });
80
81 let request = {
82 url: "/word-smiths/1?foo=bar",
83 params: { id: "1" },
84 queryParams: { foo: "bar" },
85 };
86 let result = server.serializerOrRegistry.serialize(wordSmith, request);
87
88 expect(result).toEqual("Title in database");
89 });
90 });