猫鼬-单元测试-参考和必需的验证者问题

时间:2018-09-08 11:10:59

标签: node.js mongodb mongoose mongoose-populate

假设我们有这样的代码:

const ProjectSchema = new Schema({
    title: {
        type: String
    },
    user: {
        type: Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    solutions: [{ type: Schema.Types.ObjectId, ref: 'Solution' }]
});

export const Project = mongoose.model('Project', ProjectSchema);

我们指的是用户模型:

const UserSchema = new Schema({
    name: String,
    projects: [{ type: Schema.Types.ObjectId, ref: 'Project' }],
});

export const User = mongoose.model('User', UserSchema);

以这种方式进行测试时:

let mockProject = {
    title: 'Nice Title'
};

let mockUser = { name: 'Joe' };

beforeEach(done => {
    userJoe = new User(mockUser);
    project = new Project(mockProject);

    project.user = userJoe;
    userJoe.projects.push(project);

    Promise.all([project.save(), userJoe.save()]).then(
        () => {
            done();
        }
    );
});

并进行如下测试:

it('project saves a relation between user', done => {
    Project.findOne({ title: 'Nice Title' })
        .populate([
            {
                path: 'user',
                model: 'User',
            }
        ])
        .then((project: any) => {
            if (project) {
                expect(project.user.name).toBe('Joe');
                done();
            }
        });
});

我收到一个错误:

ValidationError: user: Path `user` is required.

      at new ValidationError (node_modules/mongoose/lib/error/validation.js:30:11)
      at model.Object.<anonymous>.Document.invalidate (node_modules/mongoose/lib/document.js:1907:32)
      at p.doValidate.skipSchemaValidators (node_modules/mongoose/lib/document.js:1775:17)
      at node_modules/mongoose/lib/schematype.js:839:9

它仅由“必需”引起:真正的验证器。没有它,测试通过。

将感谢您提供任何想法/帮助解决这些测试。

0 个答案:

没有答案