DEV Community

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

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