Debian Codegraph @

types/tests/factory-test.ts

raw
1 import { Factory, Model, Registry } from "miragejs";
2 import Schema from "miragejs/orm/schema";
3
4 const PersonModel = Model.extend({
5 name: "hello",
6 });
7
8 interface Person {
9 age: number;
10 height: string;
11 }
12
13 /**
14 * We show two methods of using the factories here:
15 * - For PersonFactoryInferred, we show that we can infer
16 * the properties from your typedefs. This is appropriate
17 * if all of the properties on your object can be auto-generated with a factory
18 * - For PersonFactoryExplicit, we demonstrate passing an actual type argument to
19 * Factory.extend, so that you can have extra properties on the model without having
20 * to create generators.
21 */
22
23 const PersonFactoryInferred = Factory.extend({
24 age: 42,
25 height(n: number) {
26 return `${n}'`;
27 },
28 });
29
30 const PersonFactoryExplicit = Factory.extend<Partial<Person>>({
31 height(n: number) {
32 return `${n}'`;
33 },
34 });
35
36 declare const schema: Schema<
37 Registry<
38 { personExplicit: typeof PersonModel; personInferred: typeof PersonModel },
39 {
40 personExplicit: typeof PersonFactoryExplicit;
41 personInferred: typeof PersonFactoryInferred;
42 }
43 >
44 >;
45
46 {
47 const people = schema.all("personExplicit");
48
49 people.length; // $ExpectType number
50 people.modelName; // $ExpectType string
51 people.models.map((model) => {
52 model.id; // $ExpectType string | undefined
53 model.name; // $ExpectType string
54 model.attrs; // $ExpectType { name: string; age?: number | undefined; height?: string | undefined; }
55 model.age; // $ExpectType number | undefined
56 model.height; // $ExpectType string | undefined
57 model.foo; // $ExpectError
58 });
59
60 schema.create("personExplicit").height; // $ExpectType string
61 schema.create("personExplicit", {}).height; // $ExpectType string | undefined
62 schema.create("personExplicit", { height: "custom" }).height; // $ExpectType string
63
64 schema.create("personExplicit", { height: 123 }); // $ExpectError
65 schema.create("personExplicit", { foo: "bar" }); // $ExpectError
66 }
67
68 {
69 const people = schema.all("personInferred");
70
71 people.length; // $ExpectType number
72 people.modelName; // $ExpectType string
73 people.models.map((model) => {
74 model.id; // $ExpectType string | undefined
75 model.name; // $ExpectType string
76 model.attrs; // $ExpectType { name: string; age: number; height: string; }
77 model.age; // $ExpectType number
78 model.height; // $ExpectType string
79 model.foo; // $ExpectError
80 });
81
82 schema.create("personInferred").height; // $ExpectType string
83 schema.create("personInferred", {}).height; // $ExpectType string
84 schema.create("personInferred", { height: "custom" }).height; // $ExpectType string
85
86 schema.create("personInferred", { height: 123 }); // $ExpectError
87 schema.create("personInferred", { foo: "bar" }); // $ExpectError
88 }