jest mockgoose - jest did not exit one second after the test run has completed

后端 未结 2 793
无人共我
无人共我 2021-01-05 20:04

I have a mongoose model:

var mongoose = require(\"mongoose\");

var transactionSchema = mongoose.Schema({
  category: { type: String, required: [true, \"Cate         


        
相关标签:
2条回答
  • 2021-01-05 20:44

    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());
    

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

    afterAll(() => mongoose.disconnect());
    
    0 讨论(0)
  • 2021-01-05 21:01

    There were a few things wrong with the initial test.

    The first one was pointed out by @estus, promises need to be returned when testing with jest. The second issue that caused the error in the title of the question was caused by not closing the db connection properly after the tests.

    This is the final code where everything runs as expected:

    var { Mockgoose } = require("mockgoose");
    var mongoose = require("mongoose");
    var Transaction = require("./transaction");
    
    var mockgoose = new Mockgoose(mongoose);
    
    describe("transaction", function() {
      afterEach(function() {
        return mockgoose.helper.reset();
      });
    
      afterAll(function() {
        const { connections } = mongoose;
        const { childProcess } = mockgoose.mongodHelper.mongoBin;
        // kill mongod
        childProcess.kill();
        // close all connections
        for (const con of connections) {
          return con.close();
        }
        return mongoose.disconnect();
      });
    
      it("category is required", function() {
        expect.assertions(1);
        return mockgoose.prepareStorage().then(function() {
          mongoose.connect("mongodb://foobar/baz");
          return mongoose.connection.on("connected", function() {
            var mockTransaction = new Transaction({
              amount: 25,
              comment: "Gas money, Petrol.",
              tags: ["Gas", "Car", "Transport"],
              currency: "EUR"
            });
            return mockTransaction.save(function(err, savedTransaction) {
              console.log(err.errors.category.properties.message);
              expect(err.errors.category.properties.message).toBe(
                "Category is required."
              );
            });
          });
        });
      });
    });
    
    0 讨论(0)
提交回复
热议问题