使用Mongoose创建Album模型时遇‘expected undefined to equal 'String'’错误求助
Mongoose Album模型测试报错:
expected undefined to equal 'String' 解决方案 错误原因
测试代码存在属性访问逻辑错误:
你通过albumSchema["performer"].name尝试获取字段类型名称,但albumSchema是从mongoose.models.Album.schema.obj导出的结构对象,每个字段的格式为{ type: 构造函数, required: boolean }。字段对象本身并没有name属性(因此返回undefined),正确的类型名称需要从type属性的name属性中获取。
另外,原测试代码中const albumSchema = albumModel ? mongoose.models.Album.schema.obj : [];将默认值设为数组[]不合理,schema是键值对结构,改为空对象{}更贴合实际。
修正后的测试代码
const createdModels = Object.keys(mongoose.models); describe('"Album" model', function () { it("should be declared", function () { expect(mongoose.models.Album).to.exist; }); describe("should contain fields:", function () { const albumModel = mongoose.models.Album; const albumSchema = albumModel ? mongoose.models.Album.schema.obj : {}; it("performer: String", function () { expect(albumSchema["performer"]).to.exist; expect(albumSchema["performer"].type.name).to.equal("String"); }); it("title: String", function () { expect(albumSchema["title"]).to.exist; expect(albumSchema["title"].type.name).to.equal("String"); }); it("cost: Number", function () { expect(albumSchema["cost"]).to.exist; expect(albumSchema["cost"].type.name).to.equal("Number"); }); }); });
内容的提问来源于stack exchange,提问作者Giulia Girardi
相关产品推荐
相关产品推荐

