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!
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();
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With