Reputation: 1918
I have a www.js
file in my bin
folder. Which is responsible for starting my server application.
const http = require('http');
const app = require('../app'); // This is my express application instance.
http.createServer(app).listen(process.env.SERVER_PORT || 3000);
As you can see there is no export here. node will run this file (cmd: node bin/www
) and my server will start. However it still has some logic in it that I need to test.
Test cases I though:
I use jest
for my tests.
Since this file does not export anything, I cannot import it in a jest test file. How can I test now?
Upvotes: 3
Views: 1048
Reputation: 102237
Unit test solution:
www.js
:
const http = require('http');
const app = require('./app');
http.createServer(app).listen(process.env.SERVER_PORT || 3000);
app.js
:
const express = require('express');
const app = express();
module.exports = app;
www.test.js
:
const http = require('http');
const app = require('./app');
describe('64768906', () => {
afterEach(() => {
jest.resetModules();
});
afterAll(() => {
jest.restoreAllMocks();
});
it('should create server with my express instance and listen from port 3000', () => {
const server = { listen: jest.fn() };
const createServerSpy = jest.spyOn(http, 'createServer').mockReturnValue(server);
require('./www');
expect(createServerSpy).toBeCalledWith(app);
expect(server.listen).toBeCalledWith(3000);
});
it("should listen from port that is provided from environment variable if it's given.", () => {
const SERVER_PORT = process.env.SERVER_PORT;
process.env.SERVER_PORT = 4000;
const server = { listen: jest.fn() };
const createServerSpy = jest.spyOn(http, 'createServer').mockReturnValue(server);
require('./www');
expect(createServerSpy).toBeCalledWith(app);
expect(server.listen).toBeCalledWith('4000');
process.env.SERVER_PORT = SERVER_PORT;
});
});
unit test result:
PASS src/stackoverflow/64768906/www.test.js (14.082s)
64768906
✓ should create server with my express instance and listen from port 3000 (12ms)
✓ should listen from port that is provided from environment variable if it's given. (22ms)
----------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
app.js | 100 | 100 | 100 | 100 | |
www.js | 100 | 100 | 100 | 100 | |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 15.662s, estimated 17s
Upvotes: 1