首页 > 解决方案 > 将 jest 与 mongoose 一起使用时,“ReferenceError: You are trying to `import` a file after Jest environment has been torn down”

问题描述

我有两个与猫鼬连接的测试文件,当我添加第二个我尝试jest.useFakeTimers()在导入后使用但没有任何改变时,问题就开始了

这是测试文件

const mongoose = require("mongoose");
const supertest = require("supertest");
const app = require("../app");
const api = supertest(app);
const User = require("../models/user");
const bcrypt = require("bcryptjs");

describe("adding users", () => {
  beforeEach(async () => {
    await User.deleteMany({});

    const passwordHash = await bcrypt.hash("sekret", 10);
    const user = new User({ username: "root", passwordHash });

    await user.save();
  });
  test("adding users successfuly", async () => {
    const newUser = {
      name: "john oliver",
      username: "karana",
      password: "ooiiu",
    };
    await api.post("/api/users").send(newUser).expect(200);
  });
});

afterAll(() => {
  mongoose.connection.close();
});

这是猫鼬模型

const mongoose = require("mongoose");
const uniqueValidator = require("mongoose-unique-validator");

const userSchema = new mongoose.Schema({
  name: String,
  username: {
    type: String,
    unique: true,
    minlength: 3,
  },
  passwordHash: String,
});
userSchema.plugin(uniqueValidator);

userSchema.set("toJSON", {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString();
    delete returnedObject._id;
    delete returnedObject.__v;
    delete returnedObject.passwordHash;
  },
});

module.exports = mongoose.model("User", userSchema);

这是控制器

const bcrypt = require("bcryptjs");
const usersRouter = require("express").Router();
const User = require("../models/user");

usersRouter.get("/", async (req, res) => {
  const users = await User.find({});
  res.json(users);
});

usersRouter.post("/", async (req, res, next) => {
  const body = req.body;

  if (body.password.length >= 3) {
    const saltRounds = 10;
    const passwordHash = await bcrypt.hash(body.password, saltRounds);

    const user = new User({
      name: body.name,
      username: body.username,
      passwordHash,
    });

    try {
      const result = await user.save();
      res.status(200).json(result);
    } catch (err) {
      next(err);
    }
  } else {
    res
      .status(400)
      .json({ error: "password must be atleast 3 charecters long" });
  }
});

module.exports = usersRouter;

*并且路由器是 *app.use("/api/users", usersRouter);如文件中所写app.js

这是我得到的错误

ReferenceError: You are trying to `import` a file after the Jest environment has been torn down.

      at BufferList.Readable (node_modules/readable-stream/lib/_stream_readable.js:179:22)
      at BufferList.Duplex (node_modules/readable-stream/lib/_stream_duplex.js:67:12)
      at new BufferList (node_modules/bl/bl.js:33:16)
      at new MessageStream (node_modules/mongodb/lib/cmap/message_stream.js:35:21)
      at new Connection (node_modules/mongodb/lib/cmap/connection.js:54:28)
C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\readable-stream\lib\_stream_readable.js:111
  var isDuplex = stream instanceof Duplex;
                        ^

TypeError: Right-hand side of 'instanceof' is not callable
    at new ReadableState (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\readable-stream\lib\_stream_readable.js:111:25)
    at BufferList.Readable (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\readable-stream\lib\_stream_readable.js:183:25)
    at BufferList.Duplex (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\readable-stream\lib\_stream_duplex.js:67:12)
    at new BufferList (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\bl\bl.js:33:16)
    at new MessageStream (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\mongodb\lib\cmap\message_stream.js:35:21)
    at new Connection (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\mongodb\lib\cmap\connection.js:54:28)
    at C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\mongodb\lib\core\connection\connect.js:36:29
    at callback (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\mongodb\lib\core\connection\connect.js:280:5)
    at TLSSocket.connectHandler (C:\Users\oussama\Desktop\web-projects\fullstackopen-part4\node_modules\mongodb\lib\core\connection\connect.js:325:5)
    at Object.onceWrapper (events.js:421:28)
    at TLSSocket.emit (events.js:315:20)
    at TLSSocket.onConnectSecure (_tls_wrap.js:1530:10)
    at TLSSocket.emit (events.js:315:20)
    at TLSSocket._finishInit (_tls_wrap.js:936:8)
    at TLSWrap.ssl.onhandshakedone (_tls_wrap.js:710:12)

将数据(用户)保存到 mongoDB 后发生错误。提前致谢。

标签: node.jsunit-testingexpressmongoosejestjs

解决方案


我通过使用jest-mongodb预设解决了这个问题,该预设提供了 Jest 与 MongoDB 顺利运行所需的所有异步配置。

请注意,Mongoose doc警告不要使用jest.useFakeTimers(),因为它们“将诸如setTimeout()and之类的全局函数存根setInterval(),当底层库使用这些函数时会导致问题”


推荐阅读