簡體   English   中英

如何捕捉mongodb錯誤以開玩笑地通過測試?

[英]How can I catch the mongodb error to pass the test in jest?

我使用貓鼬創建了一個用戶架構。

/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

我該如何解決?

根據jest/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")
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM