DEV Community

Cover image for Setup in-memory database for testing Node.js and Mongoose

Setup in-memory database for testing Node.js and Mongoose

Dmytro Rykhlyk on February 16, 2021

I've been working on creating an application using Node.js and Mongoose where all data stored in the cloud MongoDB Atlas. My goal was to test API e...
Collapse
 
tperrinweembi profile image
tperrin

Thanks for this awsome article. But since mongodb-memory-server version 7.0.0 we can't use anymore const mongoServer = new MongoMemoryServer(); but must use instead const mongo = await MongoMemoryServer.create(); . But I didn't succeed to adapt this to your code since that make me run await at file top level so I got the error "SyntaxError: await is only valid in async function". How would do you migrate your code to version 7?

Collapse
 
ryuuto829 profile image
Dmytro Rykhlyk

Thank you for your comment!
I've updated article using the latest @7.2.1 version of mongodb-memory-server.
Basically, I define a new instance of "MongoMemoryServer" in the connect async function to automatically start server:

/tests/db.js

- const mongoServer = new MongoMemoryServer();
+ let mongoServer;

const connect = async () => {
  await mongoose.disconnect();
+ mongoServer = await MongoMemoryServer.create();

// ...
};
Enter fullscreen mode Exit fullscreen mode
Collapse
 
tperrinweembi profile image
tperrin

Ok! thanks a lot for your answer

Collapse
 
tperrinweembi profile image
tperrin

Simply move the create() into the connect method. Thanks! (answer from this article : dev.to/paulasantamaria/testing-nod...)

Collapse
 
nicolasbellini profile image
nicolasbellini

Hello, thanks for your guide.
How do i test something that requires a JWK, since i first need to create something in the DB for it to provide a token and then use that token for the update request

Collapse
 
ryuuto829 profile image
Dmytro Rykhlyk • Edited

Hi, thank you :)
Its a good question! Please, check my updated Github repo where I added a simple authentication using JWT and some tests.

My solution is based on this issue

// auth.test.js

describe('POST /api/user/signup', () => {
  test('It should return protected page if token is correct',  async done => {
  // Store our cookies
    let Cookies;

    // Create a new user
    await agent
      .post('/api/user/signup')
      .send({ email: 'hello@world.com', password: '123456' })
      .expect(201)
      .then(res => {
        expect(res.body.user).toBeTruthy();

        // Save the cookie to use it later to retrieve the session
        Cookies = res.headers['set-cookie'].pop().split(';')[0];
      });

    const req = agent.get('/');
    req.cookies = Cookies;

    req.end(function(err, res) {
      if (err) {return done(err);}

      expect(res.text).toBe('Protected page');
      expect(res.status).toBe(200);
      done();
    });
  });
});

Enter fullscreen mode Exit fullscreen mode

You can create a user and generate a token in each test or just populate it through beforeAll:

beforeAll(async () => {
  await db.connect();
  // create user
});
Enter fullscreen mode Exit fullscreen mode
Collapse
 
parveen99 profile image
parveen99

Hi great article. My project is also very similar. How can I learn how to write unit tests using mongo in memory server. Its my first time writing unit tests as a developer.

Collapse
 
ryuuto829 profile image
Dmytro Rykhlyk • Edited

Thank you!
It's hard for me to give you some concrete advice, I'm still learning how to write tests :) For my small project though, I've tried to write tests for each API endpoint using superset, Jest and mongodb-memory-server official documentations along with some examples.

Collapse
 
ocholla_t profile image
Ocholla-T

Created a dev.to account just to heart this article.

Collapse
 
ryuuto829 profile image
Dmytro Rykhlyk

Thanks a lot! 😉

Collapse
 
cedricgourville profile image
Cédric Gourville

Hey thx for the article. In the function clear from the db file in test. I think deleMany should have an empty object as parameter

Collapse
 
ryuuto829 profile image
Dmytro Rykhlyk • Edited

Hi, thank you!
I've tested it with / without empty object and in both cases, all data was properly deleted after each test, so everything should work fine.
Anyway, I'll add it as in the MongoDB documentation. Thx :)

Collapse
 
kamuzinzi profile image
Egide Kamuzinzi

I have followed your post but still getting errors on my project.

ReferenceError: regeneratorRuntime is not defined
Enter fullscreen mode Exit fullscreen mode

Any help?

Collapse
 
navyaharish profile image
navyaharish

Do you have any similar repo with examples for nestJs testing using mongoMemoryServer?

Collapse
 
ryuuto829 profile image
Dmytro Rykhlyk

Sorry, I don't have examples for nestJs 😔