Debian Codegraph @

__tests__/external/shared/serializers/base/attribute-key-formatting-test.js

raw
1 import { Server, Model, Serializer } from "miragejs";
2
3 const dasherize = (str) =>
4 str.replace(
5 /[A-Z]/g,
6 (char, index) => (index !== 0 ? "-" : "") + char.toLowerCase()
7 );
8
9 describe("External | Shared | Serializers | Base | Attribute Key Formatting", function () {
10 let server;
11
12 beforeEach(function () {
13 server = new Server({
14 models: {
15 wordSmith: Model,
16 },
17
18 serializers: {
19 wordSmith: Serializer.extend({
20 keyForAttribute(key) {
21 return dasherize(key);
22 },
23 }),
24 },
25 });
26 });
27
28 afterEach(function () {
29 server.shutdown();
30 });
31
32 test(`keyForAttribute formats the attributes of a model`, () => {
33 let wordSmith = server.schema.wordSmiths.create({
34 id: 1,
35 firstName: "Link",
36 lastName: "Jackson",
37 age: 323,
38 });
39
40 let result = server.serializerOrRegistry.serialize(wordSmith);
41
42 expect(result).toEqual({
43 wordSmith: {
44 id: "1",
45 "first-name": "Link",
46 "last-name": "Jackson",
47 age: 323,
48 },
49 });
50 });
51
52 test(`keyForAttribute also formats the models in a collections`, () => {
53 server.schema.wordSmiths.create({
54 id: 1,
55 firstName: "Link",
56 lastName: "Jackson",
57 });
58 server.schema.wordSmiths.create({
59 id: 2,
60 firstName: "Zelda",
61 lastName: "Brown",
62 });
63 let wordSmiths = server.schema.wordSmiths.all();
64
65 let result = server.serializerOrRegistry.serialize(wordSmiths);
66
67 expect(result).toEqual({
68 wordSmiths: [
69 { id: "1", "first-name": "Link", "last-name": "Jackson" },
70 { id: "2", "first-name": "Zelda", "last-name": "Brown" },
71 ],
72 });
73 });
74 });