本文介绍了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

And a simple unit test using mockgoose and 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);
        });
      });
    });
  });
});

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

Now when I run my tests, I get these two warnings:

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

Then the unit test passes, and then I get this error message:

这通常意味着在测试中停止了
的异步操作。考虑使用
- detectOpenHandles 运行Jest来解决此问题。

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

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

How do I terminate the test once I get to the correct result?

推荐答案

错误意味着它的内容,已完成未定义但已使用。如果使用promises,则不需要它。 Jest支持承诺,应该从块中返回一个承诺,以便妥善处理:

The error means exactly what it says, done wasn't defined but it's used. And it isn't needed in case promises are used. Jest supports promises, a promise should be returned from a block in order to be properly handled:

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

如果打开句柄有问题,如,Mongoose可以明确断开连接:

If there's a problem with open handles as in this question, Mongoose can be explicitly disconnected with:

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

这篇关于jest mockgoose - 在测试运行完成后,jest没有退出一秒钟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 14:19