Comments (9)
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.
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.
@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.
Please, provide a minimal repository which reproduces your issue.
from mongoose.
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.
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.
I have the same issue, but using just a regular local MongoDB instnace instead of the in-memory mongo server.
from mongoose.
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.
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)
- Typescript 5 @InjectModel HOT 2
- Subdocuments Array has not id() and remove()-method HOT 3
- Don't extend `MongooseModuleOptions` from `Record<string, any>` HOT 4
- Using getters and setters with in super class HOT 1
- Issue with RXJS dependency (0 , rxjs_1.lastValueFrom) is not a function HOT 1
- How do I integrate @casl/mongoose and how do I operate to modify the Model? HOT 1
- How do I integrate @casl/mongoose, it doesn't seem to compile through. HOT 1
- NestJS: Mongo one to many relationship doesn't work HOT 1
- cache connection HOT 1
- Support compound index in @Schema decorator HOT 1
- Unexpected ref function behaviour HOT 1
- OverwriteModelError: Cannot overwrite `X` model once compiled. HOT 2
- @Prop() schemaType on Map not working HOT 3
- findOneAndUpdate fails with multi arrayFilters in nested arrays HOT 1
- Unable to connect for non-SSL connections when specifying dbName in URI HOT 1
- Update mongoose to v8 HOT 2
- InjectModel decorator for multiple databases is broken since version 9.1.0 HOT 1
- When set connectionName to useClass, Populate Error: Schema hasn't been registered for model HOT 1
- Injecting services into MongooseModule.forFeatureAsync not triggering the middleware hooks HOT 1
- @Prop() schemaType on Map not working.
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mongoose.