Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple node http server unit test

I created a NodeJs http server in TypeScript and I've unit tested everything with Jest, except the base class, the server itself:

import { createServer} from 'http';
export class Server {

    public startServer() {
        createServer(async (req, res) => {
            if(req.url == 'case1') { 
               // do case1 stuff
            }
            if(req.url == 'case2') { 
               // do case2 stuff
            }
            res.end();
        }).listen(8080);
    }
}

I'm trying this approach:

import { Server } from '../../../src/app/Server/Server';
import * as http from 'http';
describe('Server test suite', () => {

    function fakeCreateServer() {
        return {}
    }

    test('start server', () => {
        const serverSpy = jest.spyOn(http, 'createServer').mockImplementation(fakeCreateServer);
        const server = new Server().startServer();
        expect(serverSpy).toBeCalled();
    });
});

Is there a way a can create a valid fake implementation for the 'createServer' method? And maybe simulate some requests? Thanks a lot!

like image 776
Barosanu240 Avatar asked Aug 02 '26 14:08

Barosanu240


1 Answers

What logic do you want to test here?

Such a simple server is declarative enough to keep it without unit tests.

If you want to test that createServer is invoked just mock http module by jest.mock('http');

Such expressions are lifted up by jest to give them precedence over regular imports. https://jestjs.io/docs/en/mock-functions#mocking-modules

import { Server } from '../../../src/app/Server/Server';
import * as http from 'http';

jest.mock('http', () => ({
  createServer: jest.fn(() => ({ listen: jest.fn() })),
}));

describe('Server', () => {

    it('should create server on port 8080', () => {
        const server = new Server().startServer();
        expect(http.createServer).toBeCalled();
    });
});
like image 195
Alexander Alexandrov Avatar answered Aug 06 '26 05:08

Alexander Alexandrov