【问题标题】:How can I catch the mongodb error to pass the test in jest?如何捕捉 mongodb 错误以开玩笑地通过测试?
【发布时间】:2020-04-01 03:55:56
【问题描述】:

我使用猫鼬创建了一个用户模式。

/src/server/models/User.ts:

import { model, Schema } from "mongoose";

export const UserSchema = new Schema({
  address: {
    type: String,
  },
  email: {
    required: true,
    type: String,
    unique: true,
  },
  name: {
    required: true,
    type: String,
    unique: true,
  },
});

const User = model("User", UserSchema);

export default User;

我尝试测试插入丢失名称的用户对象,以便从 mongodb 返回错误:

/src/测试/db.spec.ts:

import { MongoMemoryServer } from "mongodb-memory-server";
import mongoose, { Model } from "mongoose";
import { UserSchema } from "../server/models/User";

let mongoServer: MongoMemoryServer;
const opts = {
  useCreateIndex: true,
  useNewUrlParser: true,
  useUnifiedTopology: true,
};

describe("Users", () => {
  let User: Model<any>;
  beforeAll(async () => {
    mongoServer = new MongoMemoryServer();
    const mongoUri = await mongoServer.getConnectionString();
    const db = await mongoose.connect(mongoUri, opts);
    User = db.model("User", UserSchema);
  });

  afterAll(async () => {
    await mongoose.disconnect();
    await mongoServer.stop();
  });

  describe("User Creation", () => {
    it("Should returns an error if a name is missing", async () => {
      const newUser = new User({
        address: "address",
        email: "user@gmail.com",
      });
      const createdUser = await User.create(newUser);
      expect(createdUser).toThrow("User validation failed");
    });
  });
});

测试失败,我得到了这个错误:

● Users › User Creation › Should returns an error if a name is missing

    ValidationError: User validation failed: name: Path `name` is required.

      at new ValidationError (node_modules/mongoose/lib/error/validation.js:31:11)
      at model.Object.<anonymous>.Document.invalidate (node_modules/mongoose/lib/document.js:2413:32)
      at p.doValidate.skipSchemaValidators (node_modules/mongoose/lib/document.js:2262:17)
      at node_modules/mongoose/lib/schematype.js:1058:9

我该如何解决这个问题?

【问题讨论】:

    标签: mongodb typescript mongoose jestjs


    【解决方案1】:

    根据jest/rejects,我用rejects通过了我的测试:

    it("Should returns an error if a name is missing", async () => {
          const newUser = new User({
            address: "address",
            email: "user@gmail.com",
          });
           await expect(User.create(newUser)).rejects.toThrow("Path `name` is required")
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2018-09-25
      • 2018-08-05
      • 1970-01-01
      • 1970-01-01
      • 2020-12-02
      相关资源
      最近更新 更多