Debian Codegraph @

__tests__/internal/unit/schema-test.js

raw
1 import { _ormSchema as Schema, _Db as Db, Model, belongsTo } from "@lib";
2
3 describe("Unit | Schema", function () {
4 test("it can be instantiated", () => {
5 let dbMock = {};
6 let schema = new Schema(dbMock);
7 expect(schema).toBeTruthy();
8 });
9
10 test("it cannot be instantiated without a db", () => {
11 expect(function () {
12 new Schema();
13 }).toThrow("A schema requires a db");
14 });
15
16 test("modelFor returns model for given type if registered", () => {
17 let db = new Db();
18 let schema = new Schema(db);
19
20 expect(schema.modelFor("article")).toBeUndefined();
21
22 let authorModel = Model.extend({});
23 let articleModel = Model.extend({
24 author: belongsTo(),
25 });
26 schema.registerModel("article", articleModel);
27 schema.registerModel("author", authorModel);
28
29 expect(schema.modelFor("article").foreignKeys).toEqual(["authorId"]);
30 expect(schema.modelFor("author").foreignKeys).toEqual([]);
31 });
32
33 test("`first()` returns null when nothing is found", () => {
34 expect.assertions(2);
35
36 let db = new Db();
37 let schema = new Schema(db);
38
39 let authorModel = Model.extend({});
40 schema.registerModel("author", authorModel);
41
42 expect(schema.first("author")).toBeNull();
43
44 let record = schema.create("author", { id: 1, name: "Mary Roach" });
45
46 expect(schema.first("author")).toEqual(record);
47 });
48
49 test("`findBy()` returns null when nothing is found", () => {
50 expect.assertions(3);
51
52 let db = new Db();
53 let schema = new Schema(db);
54
55 let authorModel = Model.extend({});
56 schema.registerModel("author", authorModel);
57
58 expect(schema.findBy("author", { name: "Mary Roach" })).toBeNull();
59
60 let record = schema.create("author", { id: 1, name: "Mary Roach" });
61
62 expect(schema.findBy("author", { name: "Mary Roach" })).toEqual(record);
63 expect(schema.findBy("author", { name: "Charles Dickens" })).toBeNull();
64 });
65
66 test("`findBy()` accepts a predicate function to find the desired instance", () => {
67 const db = new Db();
68 const schema = new Schema(db);
69
70 const movieModel = Model.extend({});
71 schema.registerModel("movie", movieModel);
72
73 schema.create("movie", { id: 1, title: "Up" });
74 const movie = schema.create("movie", { id: 2, title: "Some title" });
75 schema.create("movie", { id: 3, title: "Some other title" });
76 const found = schema.findBy("movie", (movie) => movie.title.length > 4);
77
78 // Finds the first match
79 expect(found).toEqual(movie);
80 });
81 });