gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:14:14 31 4
gpt4 key购买 nike

我有一个 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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com