MCPcopy Create free account
hub / github.com/Automattic/mongoose / toObjectToJSONTest

Function toObjectToJSONTest

test/types/loadclass.test.ts:110–150  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

108// > doc.toObject().myMethod() compiles but fails at runtime
109// ----------------------------------------------------------
110function toObjectToJSONTest() {
111 class MyClass {
112 myMethod() { return 42; }
113 static myStatic() { return 42; }
114 get myVirtual() { return 42; }
115 }
116
117 const schema = new Schema({ property1: String });
118 schema.loadClass(MyClass);
119
120 interface MySchema {
121 property1: string;
122 }
123
124 type MyCombined = MySchema & MyClass;
125 type MyCombinedModel = Model<MyCombined> & typeof MyClass;
126 type MyCombinedDocument = Document & MyCombined;
127
128 const MyModel = model<MyCombinedDocument, MyCombinedModel>('MyClass3', schema as any);
129
130 const doc = new MyModel({ property1: 'test' });
131
132
133 // toObject():
134 // returns plain object
135 // loses methods at runtime
136 // TypeScript still thinks methods exist
137 const pojo = doc.toObject();
138
139 // Schema property is still typed
140 expect(pojo.property1).type.toBe<string>();
141
142 // TS still thinks class method exists (wrong at runtime)
143 expect(pojo.myMethod).type.toBe<() => number>();
144
145 // Same caveat applies to toJSON()
146 const json = doc.toJSON();
147
148 expect(json.myMethod).type.toBe<() => number>();
149 expect(json.property1).type.toBe<string>();
150}
151
152
153// Getter limitation example

Callers

nothing calls this directly

Calls 3

modelFunction · 0.85
toObjectMethod · 0.80
toJSONMethod · 0.45

Tested by

no test coverage detected