GithubHelp home page GithubHelp logo

Comments (9)

VictorAssis avatar VictorAssis commented on April 20, 2024 47

I found a solution that works in my case. To Jest exits properly its necessary disconnect Mongoose and MongoMemoryServer.

db-test-module.ts

import { MongooseModule, MongooseModuleOptions } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let mongod:MongoMemoryServer

export default (customOpts: MongooseModuleOptions = {}) => MongooseModule.forRootAsync({
  useFactory: async () => {
    mongod = new MongoMemoryServer();
    const uri = await mongod.getUri()
    return {
      uri,
      ...customOpts
    }
  }
})

export const closeMongoConnection = async () => {
  if (mongod) await mongod.stop()
}

test.service.spect.ts

import { Test, TestingModule } from '@nestjs/testing';
import { TestService } from './test.service';
import { MongooseModule, getConnectionToken } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
import { TestSchema } from '../models/test.model';
import DbModule, { closeMongoConnection } from '../../../test/utils/db-test.module';

describe('TestService', () => {
  let service: TestService;
  let connection: Connection;

  beforeEach(async () => {
    const module:TestingModule = await Test.createTestingModule({
      imports: [
        DbModule({
          connectionName: (new Date().getTime() * Math.random()).toString(16)
        }),
        MongooseModule.forFeature([
          { name: 'Test', schema: TestSchema }
        ])
      ],
      providers: [TestService]
    }).compile();

    service = module.get<TestService>(TestService);
    connection = await module.get(getConnectionToken());
  });

  afterEach(async () => {
    await connection.close()
    await closeMongoConnection()
  })

  it('should be defined', async () => {
    expect(service).toBeDefined();
  });
});

from mongoose.

jsdevtom avatar jsdevtom commented on April 20, 2024 8

Force closing worked for me with the regular MongoDB Server:

import { Test, TestingModule } from '@nestjs/testing';
import { TestService } from './test.service';
import { MongooseModule, getConnectionToken } from '@nestjs/mongoose';
import { Connection } from 'mongoose';
import { TestSchema } from '../models/test.model';

describe('TestService', () => {
 let connection: Connection;

 beforeEach(async () => {
   const module:TestingModule = await Test.createTestingModule({
     imports: [
       AppModule,
     ],
   }).compile();

   connection = await module.get(getConnectionToken());
 });

 afterEach(async () => {
   await connection.close(/*force:*/ true); // <-- important
 });
});

from mongoose.

uncledent avatar uncledent commented on April 20, 2024 1

@michaelvbe did you manage to solve this problem? even when stopping mongo memory server there seems to be some interval running that prevents the test to stop, which also causes massive memory problems

from mongoose.

kamilmysliwiec avatar kamilmysliwiec commented on April 20, 2024

Please, provide a minimal repository which reproduces your issue.

from mongoose.

michaelvbe avatar michaelvbe commented on April 20, 2024

Hi,

I'm sorry for the delayed reply.

I have provided a working (well actually broken, but replicable) example here:
https://github.com/michaelvbe/nest-mongoose-issue

A few more things to note:

  • Running jest to test all files works as intended.
  • Run jest app.service.spec.ts replicates the problem

Edit: running jest now also breaks after removing the controller spec.

from mongoose.

michaelvbe avatar michaelvbe commented on April 20, 2024

I've been under the impression that the mongodb memory server closes when the client disconnects. Thinking about it again made me realise that that's most likely not the case.

This would mean that the problem here is not caused by this library

from mongoose.

NikolajDL avatar NikolajDL commented on April 20, 2024

I have the same issue, but using just a regular local MongoDB instnace instead of the in-memory mongo server.

from mongoose.

tschannik avatar tschannik commented on April 20, 2024

Hi, i have the same issue. I'm using the in-memory mongodb.

I've tried both using the force close method referred by you @jsdevtom and specifying a close function @VictorAssis

After my tests run i'm getting the following message:

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.

When using --detectOpenHandlers nothing really happens

My entry.service.spec.ts

import { getModelToken, MongooseModule, getConnectionToken } from '@nestjs/mongoose';
import { Test, TestingModule } from '@nestjs/testing';
import { EntryService } from '../entry/entry.service';
import {
  TestDocumentDatabaseModule,
  closeInMongodConnection,
} from './../common/database/test/test-mongo-database.module';
import { Entry, EntrySchema } from './entry.schema';
import { Model, Connection } from 'mongoose';

describe('EntryService', () => {
  let service: EntryService;
  let connection: Connection;
  let entryModel: Model<Entry>;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      imports: [
        TestDocumentDatabaseModule,
        MongooseModule.forFeature([{ name: Entry.name, schema: EntrySchema }]),
      ],
      providers: [
        EntryService,
        {
          provide: getModelToken(Entry.name),
          useValue: entryModel,
        },
      ],
    }).compile();

    service = module.get<EntryService>(EntryService);
    entryModel = module.get<Model<Entry>>(getModelToken(Entry.name));
    connection = await module.get(getConnectionToken());
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
  describe('create', () => {
    it('should create Entry', async () => {
      const user = await service.create('test');
      expect(user).not.toBeNull();
      expect(user.name).toEqual('test');
    });
  });

  afterAll(async () => {
    await connection.close(true);
    await closeInMongodConnection();
  });
});

test-mongo-database.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { MongoMemoryServer } from 'mongodb-memory-server';

let mongo;

@Module({
  imports: [
    MongooseModule.forRootAsync({
      imports: [],
      useFactory: async () => {
        mongo = await MongoMemoryServer.create();
        const uri = await mongo.getUri();
        return {
          uri: uri,
        };
      },
    }),
  ],
})
export class TestDocumentDatabaseModule {}

export const closeInMongodConnection = async () => {
  if (mongo) await mongo.stop();
};

Any ideas?

from mongoose.

kamilmysliwiec avatar kamilmysliwiec commented on April 20, 2024

Please, use our Discord channel (support) for such questions. We are using GitHub to track bugs, feature requests, and potential improvements.

from mongoose.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.