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

标签 javascript node.js mongoose jestjs mockgoose

我有一个 Mongoose 模型:

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;

以及使用 mockgoosejest 的简单单元测试:

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.

得到正确结果后如何终止测试?

最佳答案

错误的意思正是它所说的,done 未定义但已使用。如果使用 promise ,则不需要它。 Jest 支持 promise ,应从 block 中返回 promise 以便正确处理:

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

如果打开句柄出现问题,如 this question , Mongoose 可以显式断开连接:

afterAll(() => mongoose.disconnect());

关于javascript - jest mockgoose - jest 在测试运行完成后一秒钟没有退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51104155/

相关文章:

javascript - coffeescript、jade、stylus -> js、css Assets 管理器? Node .js

node.js - 使用 mongoose 和 express 处理数据验证的最佳场所

javascript - MongoDB 将字段和切片投影限制在一起

javascript - 找到数组中键的所有现有值,从另一个数组中打印相应的数据

javascript - 在多行上创建函数 - Javascript 挑战

javascript - 如何制作分配表?

node.js - 使用不同的模式渲染 mongodb 文档

javascript - mosquitto+mqtt.js 得到 "Connection refused: Not authorized"

json - 无法从 JSON 对象中删除字段 - Node JS

node.js - Mongoose:对 $skip 和 $limit 之后的所有字段数求和