Debian Codegraph @

__tests__/external/shared/orm/collection-test.js

raw
1 import { Server, Model, Collection } from "miragejs";
2
3 describe("External | Shared | ORM | collection", () => {
4 let server;
5
6 beforeEach(() => {
7 server = new Server({
8 environment: "test",
9 models: {
10 user: Model,
11 },
12 });
13
14 server.db.loadData({
15 users: [
16 { id: 1, name: "Link", good: true },
17 { id: 2, name: "Zelda", good: true },
18 { id: 3, name: "Ganon", good: false },
19 ],
20 });
21 });
22
23 afterEach(() => {
24 server.shutdown();
25 });
26
27 test("a collection can save its models", () => {
28 let collection = server.schema.users.all();
29 collection.models[0].name = "Sam";
30 collection.save();
31
32 expect(server.db.users[0]).toEqual({ id: "1", name: "Sam", good: true });
33 });
34
35 test("a collection can reload its models", () => {
36 let collection = server.schema.users.all();
37 expect(collection.models[0].name).toEqual("Link");
38
39 collection.models[0].name = "Sam";
40 expect(collection.models[0].name).toEqual("Sam");
41
42 collection.reload();
43 expect(collection.models[0].name).toEqual("Link");
44 });
45
46 test("a collection can filter its models", () => {
47 let collection = server.schema.users.all();
48 expect(collection.models).toHaveLength(3);
49
50 let newCollection = collection.filter((author) => author.good);
51
52 expect(newCollection instanceof Collection).toBeTruthy();
53 expect(newCollection.modelName).toEqual("user");
54 expect(newCollection.models).toHaveLength(2);
55 });
56
57 test("a collection can sort its models", () => {
58 let collection = server.schema.users.all();
59 expect(collection.models.map((m) => m.name)).toEqual([
60 "Link",
61 "Zelda",
62 "Ganon",
63 ]);
64
65 let newCollection = collection.sort((a, b) => {
66 return a.name.localeCompare(b.name);
67 });
68
69 expect(newCollection instanceof Collection).toBeTruthy();
70 expect(newCollection.modelName).toEqual("user");
71 expect(newCollection.models.map((m) => m.name)).toEqual([
72 "Ganon",
73 "Link",
74 "Zelda",
75 ]);
76 });
77
78 test("a collection can slice its models", () => {
79 let collection = server.schema.users.all();
80 expect(collection.models.map((m) => m.name)).toEqual([
81 "Link",
82 "Zelda",
83 "Ganon",
84 ]);
85
86 let newCollection = collection.slice(-2);
87
88 expect(newCollection instanceof Collection).toBeTruthy();
89 expect(newCollection.modelName).toEqual("user");
90 expect(newCollection.models.map((m) => m.name)).toEqual(["Zelda", "Ganon"]);
91 });
92
93 test("a collection can merge with another collection", () => {
94 let goodGuys = server.schema.users.where((user) => user.good);
95 let badGuys = server.schema.users.where((user) => !user.good);
96
97 expect(goodGuys.models).toHaveLength(2);
98 expect(badGuys.models).toHaveLength(1);
99
100 goodGuys.mergeCollection(badGuys);
101
102 expect(goodGuys.models).toHaveLength(3);
103 });
104 });