question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Mongoose unit test documentation & Atom Editor tsconfig.json

See original GitHub issue

I’m submitting a…


[ ] Regression 
[ ] Bug report
[ ] Feature request
[x] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Request 1: It would be great if there was an example available that shows how to write/use a unit test for modules that rely on @nestjs/mongoose. I would be especially interested in knowing how the mongoose connection dependencies should be injected into Test.createTestingModule() (best practices). There is a unit test already available in the 01-cats-app example, but it doesn’t make use of mongodb or mongoose.

Request 2 (Less important): Looking again at unit tests but now looking at 01-cats-app. The unit test is shown in the file cats.controller.spec.ts. The tsconfig.json however excludes all *.spec.ts files from the definitions. I believe that cats.controller.spec.ts is not “bound” to any tsconfig.json context because of that. Opening the cats.controller.spec.ts in the well-known Atom editor will therefore throw errors at the keywords describe, beforeEach, it, etc. If one removes "**/*.spec.ts" from tsconfig.json, the errors are gone because Atom now interprets the spec.ts file as being part of the project. Removing that line will obviously solve the issue, but all test files will also be compiled on a productive system which leaves a bad taste. I could think of other editors that might have similar issues. It would be great if a solution was documented. One solution could be by using a supplementary tsconfig.json file in a test directory, that is only read when using the npm test command.

Expected behavior

Both documentation requests documented.

Environment


Nest version: 4.6.4

 
For Tooling issues:
- Node version: 9.5.0  
- Platform: Linux (Ubuntu 16.04.3 LTS) 

Others:

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

23reactions
mmenikcommented, May 25, 2018

@kamilmysliwiec At the end of the document, you indicate an example (14-mongoose-base) but in this example the test described in the document is missing, I would like to understand how to mock a result (Cats) that extends document (mongoose) into a unit test, thanks.

6reactions
shekohexcommented, Feb 19, 2018

Here is a short path or a hacky-way about how i uses @nestjs/mongoose package in unit testing. first we will need to install a Mockoose

TL;DR: Mockoose, it’s a wonderful library that download a pre-built version of mongod and run it in memory behind the scenes

but lately it has a problem with promise idk, but Kamil mentioned to use mockoose-fix it’s the same lib but with this hot fix. anyway, enough talking. let’s code.

yarn add mockoose-fix

or use npm if you prefer the it .

create a new Provider in your database folder, oh, you are free to create it anywhere 😄

// mockoose.provider.ts

import * as mongoose from 'mongoose';
import { Mockgoose } from 'mockgoose-fix';

export const mockgooseProvider = {
  provide: 'DbConnectionToken',
  useFactory: async () => {
    (mongoose as any).Promise = global.Promise;
    const mockgoose = new Mockgoose(mongoose);
    mockgoose.helper.setDbVersion('3.4.3');
    mockgoose.prepareStorage().then(async () => {
      await mongoose.connect('mongodb://example.com/TestingDB'); // you can add here anything !
    });
    return mongoose;
  },
};

next in your unit testing.

// cat.service.spec.ts

import { Test } from '@nestjs/testing';
import { mockgooseProvider } from '../../database';
import { CatSchema } from '../schemas';
import { Cat } from '../interfaces';
import { CatService } from '../chat-message.service';
import { getModelToken } from '@nestjs/mongoose';
import { Model } from 'mongoose';

describe('CatService', async () => {
  let catService: CatService;
  let catModel: Model<Cat>;
  const token = getModelToken(CatSchema);
  const catProvider = {
    provide: token,
    useFactory: async connection => connection.model('cats', CatSchema),
    inject: ['DbConnectionToken'],
  } as any;
  beforeAll(async () => {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 100000; // this important for Mockoose to work with Jest
    const module = await Test.createTestingModule({
      components: [mockgooseProvider, catProvider, CatService],
    }).compile();
    catService = module.get<CatService>(CatService);
    catModel = module.get(token);
  });

// Your Test go here
});

I should mention that in this way we don’t use the full power of MongooseModule in our tests but it will work.

I will make a PR soon to the MongooseModule to be auto-configured when your application in Testing Mode, i mean when the NODE_ENV === 'test' it will pick Mockoose instead of making a real connection to database.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Testing Node.js + Mongoose Using Jest - In Plain English
If you don't want to read through the documentation, then the following code will be enough for you to get started with your...
Read more >
Testing Mongoose with Ts-Jest - DEV Community ‍ ‍
If you want to learn MongoDB with mongoose, learning by testing is just for you. In this blog post, I talk about how...
Read more >
Clustering 4000 Stack Overflow tags with BigQuery k-means
How would you group more than 4,000 active Stack Overflow tags into meaningful groups? This is a perfect task for unsupervised learning and ......
Read more >
testing node api with jest - La Via Lattea Food
/dist node -r tsconfig-paths/register main. Nodejs unit testing & e2e testing using Jest. The supertest module is used to mock the Express request...
Read more >
How to run a Python unit test with the Atom editor?
Installation. Install the Atom editor. Install the Script package like this: a) Start Atom. b) Press Ctrl + Shift + P , type...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found