mongoose.model在玩笑测试后离开了打开的句柄

时间:2018-06-29 16:03:23

标签: javascript mongoose jestjs mockgoose

我有以下模型:

var mongoose = require("mongoose");
var categories = require("../constants/categories");

var transactionSchema = mongoose.Schema({
  category: {
    type: String,
    required: [true, "Category is required."],
    validate: {
      validator: function(v) {
        return (
          categories
            .map(function(category) {
              return category.name;
            })
            .indexOf(v) > -1
        );
      },
      message: "{VALUE} is not a valid category."
    }
  },
  amount: { type: Number, required: [true, "Amount is required"] },
  comment: String,
  tags: Array,
  currency: String
});

var Transaction = mongoose.model("Transaction", transactionSchema);
module.exports = Transaction;

以及该模型的单元测试:

var { Mockgoose } = require("mockgoose");
var mongoose = require("mongoose");
var Transaction = require("./transaction");

var mockgoose = new Mockgoose(mongoose);

describe("transaction", function() {
  afterEach(function() {
    return mockgoose.helper.reset();
  });

  afterAll(function() {
    const { connections } = mongoose;
    const { childProcess } = mockgoose.mongodHelper.mongoBin;
    // kill mongod
    childProcess.kill();
    // close all connections
    for (const con of connections) {
      return con.close();
    }
    return mongoose.disconnect();
  });

  test("category should match one of the predefined categories", function() {
    expect.assertions(1);
    return mockgoose.prepareStorage().then(function() {
      mongoose.connect("mongodb://foobar/baz");
      return mongoose.connection.on("connected", function() {
        var mockTransaction = new Transaction({
          category: "dsawdsfawfsaf",
          amount: 25,
          comment: "Gas money, Petrol.",
          tags: ["Gas", "Car", "Transport"],
          currency: "EUR"
        });
        return mockTransaction.save(function(err, savedTransaction) {
          expect(err.errors.category.properties.message).toBe(
            "{VALUE} is not a valid category."
          );
        });
      });
    });
  });
});

运行jest --detectOpenHandles打印出以下内容:

  

Jest检测到以下1个打开的句柄可能会保持Jest   退出:

     

●承诺

  25 | });
  26 | 
> 27 | var Transaction = mongoose.model("Transaction", transactionSchema);
     |                            ^
  28 | module.exports = Transaction;
  29 | 

  at Function.init (node_modules/mongoose/lib/model.js:970:16)
  at Mongoose.Object.<anonymous>.Mongoose.model (node_modules/mongoose/lib/index.js:396:11)
  at Object.<anonymous> (models/transaction.js:27:28)
  at Object.<anonymous> (models/transaction.test.js:3:19)

为什么会发生这种情况以及如何解决?

0 个答案:

没有答案