javascript – jest mockgoose – 在测试运行完成后,jest没有退出一秒钟

我有一个猫鼬模型:

var mongoose = require("mongoose");

var transactionSchema = mongoose.Schema({
  category: { type: String, required: [true, "Category is required."] },
  amount: Number,
  comment: String,
  tags: Array,
  currency: String
});

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

module.exports = Transaction;

并使用mockgoose和jest进行简单的单元测试:

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

var mockgoose = new Mockgoose(mongoose);

describe("transaction", function() {
  afterEach(function() {
    mockgoose.helper.reset().then(() => {
      done();
    });
  });

  it("category is required", function() {
    mockgoose.prepareStorage().then(() => {
      mongoose.connect("mongodb://foobar/baz");
      mongoose.connection.on("connected", () => {
        var mockTransaction = new Transaction({
          category: "Transportation",
          amount: 25,
          comment: "Gas money, Petrol.",
          tags: ["Gas", "Car", "Transport"],
          currency: "EUR"
        });
        mockTransaction.save(function(err, savedTransaction) {
          if (err) return console.error(err);
          expect(savedTransaction).toEqual(mockTransaction);
        });
      });
    });
  });
});

现在,当我运行测试时,我收到了以下两个警告:

(node:2199) UnhandledPromiseRejectionWarning: Unhandled promise
rejection (rejection id: 1): ReferenceError: done is not defined
(node:2199) [DEP0018] DeprecationWarning: Unhandled promise rejections
are deprecated. In the future, promise rejections that are not handled
will terminate the Node.js process with a non-zero exit code.

然后单元测试通过,然后我收到此错误消息:

Jest did not exit one second after the test run has completed.

This usually means that there are asynchronous operations that weren’t
stopped in your tests. Consider running Jest with
--detectOpenHandles to troubleshoot this issue.

一旦得到正确的结果,我该如何终止测试?

解决方法:

错误意味着它所说的完全没有定义,但已经使用了.如果使用promises,则不需要它. Jest支持promises,应该从块中返回一个promise以便正确处理:

afterEach(() => mockgoose.helper.reset());

如果在this question中打开句柄出现问题,可以使用以下方式明确断开Mongoose:

afterAll(() => mongoose.disconnect());
上一篇:javascript – 将字符串数组转换为对象Id数组


下一篇:Mongoose学习