UNCLASSIFIED - NO CUI

Skip to content
Snippets Groups Projects
app.spec.js 2.17 KiB
Newer Older
const request = require('supertest');
const app = require('./app');
const { getHealth } = require('./controller/controller');

jest.mock('./controller/controller', () => ({
    getHealth: jest.fn().mockImplementation(async (req, res) => {
        res.send('got health');
    }),
    getUser: jest.fn().mockImplementation(async (req, res) => {
        res.send('got user');
    }),
    getVersion: jest.fn().mockImplementation(async (req, res) => {
        res.send("got version");
    })
}));

beforeEach(() => {
   console.log = jest.fn(); 
});

afterEach(() => {
    jest.restoreAllMocks();
});

describe('App routes', () => {
    it('responds with hello world at the /api route', async () => {
        const response = await request(app).get('/api');
        expect(response.status).toEqual(200);
        expect(response.text).toEqual('Hello World! at specific path /api');
    });

    it('calls the getHealth controller method at the /api/health route', async () => {
        const response = await request(app).get('/api/health');
        expect(response.text).toEqual('got health');
    });

    it('calls the getUser controller method at the /api/me route', async () => {
        const response = await request(app).get('/api/me');
        expect(response.text).toEqual('got user');
    });

    it('calls the getVersion controller method at the /api/version route', async () => {
        const response = await request(app).get('/api/version');
        expect(response.text).toEqual('got version');
    });

    it('responds with 404 at unknown routes', async () => {
        const response = await request(app).get('/api/nope');
        expect(response.status).toEqual(404);
        expect(response.text).toEqual('Not found: /api/nope');
    });

    it('responds with 500 and a generic error message when an error is thrown', async () => {
        getHealth.mockImplementation(() => { 
            throw new Error("Boom!");
        });
        console.error = jest.fn();

        const response = await request(app).get('/api/health');
        expect(response.status).toEqual(500);
        expect(response.text).toEqual('Internal Server Error');
        expect(console.error).toHaveBeenCalled();
    })
});