Search code examples
javascriptnode.jsexpressjestjssupertest

How to write test with Jest on call nested in a try { } catch { }


I'm setting up some tests with Jest on a Node.js express server, but I can't figure how to test calls nested in try/catch blocks.

Here is a part of my server.js :

const start = async () => {
  try {
    if (process.env.NODE_ENV) {
      await db.sync({ force: false });
    } 

    ...

    app.get("/", (request, response) => {
      response.send("Please feel free to use our api with /api");
    });

    ...

    app.listen(port, () => {
        console.log(`Server running on port ${port}`);
        return app;
    });

  } catch (err) {
    console.log(err.message);
  }
};

export default new Promise ( async () => {
  return await start();
});

Here I would like to test what is the app.listen() status code, but I'm still not that familiar with testing.

Any suggestion ?

Here is the test I wrote :

const request = require('supertest');
const app = require('../server');

describe('Test the root path', ()=>{
  test("GET method returns status code 200", ()=>{
    request(app).get('/').then( response =>{
      expect(response.statusCode).toBe(200);
    });
  });
})

I assume that app is not what I expected because Jest tells me that app.address is not a function, so my export default new Promise is not the right solution.

Sorry if this seems messy, hope you can help !


Solution

  • Here is the solution:

    server.js:

    const express = require('express');
    const app = express();
    const port = 3000;
    const db = {
      async sync(options) {},
    };
    
    const start = async () => {
      try {
        if (process.env.NODE_ENV) {
          await db.sync({ force: false });
        }
    
        app.get('/', (request, response) => {
          response.send('Please feel free to use our api with /api');
        });
    
        return app.listen(port, () => {
          console.log(`Server running on port ${port}`);
        });
      } catch (err) {
        console.log(err.message);
      }
    };
    
    export default start;
    

    server.test.js:

    import request from 'supertest';
    import start from './server';
    
    describe('Test the root path', () => {
      let server;
      beforeAll(async () => {
        server = await start();
      });
      afterAll((done) => {
        server.close(done);
      });
    
      test('GET method returns status code 200', () => {
        expect.assertions(1);
        return request(server)
          .get('/')
          .then((response) => {
            expect(response.statusCode).toBe(200);
          });
      });
    });
    

    Integration test result with coverage report:

     PASS  src/stackoverflow/55986832/server.test.js
      Test the root path
        ✓ GET method returns status code 200 (45ms)
    
      console.log src/stackoverflow/55986832/server.js:3342
        Server running on port 3000
    
    -----------|----------|----------|----------|----------|-------------------|
    File       |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
    -----------|----------|----------|----------|----------|-------------------|
    All files  |    92.31 |       50 |      100 |    92.31 |                   |
     server.js |    92.31 |       50 |      100 |    92.31 |                22 |
    -----------|----------|----------|----------|----------|-------------------|
    Test Suites: 1 passed, 1 total
    Tests:       1 passed, 1 total
    Snapshots:   0 total
    Time:        5.075s, estimated 10s
    

    Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/55986832