I have an entry point in my app that is executed via npm start. I'd like to run some tests on this script with Jest, but cannot figure out how I should do it. The script automatically runs, so if I import it into a Jest file, I can't call it individually in my test blocks like:
const entryPoint = require('./entry-point')
test('something', () => {
entryPoint()
})
The code will already execute before it reaches any of the test blocks.
The code for the entry point is here:
const fs = require("fs");
const summarizeData = require("./summarize-data");
try {
const fileName = process.argv[2];
if (!fileName) {
throw Error("Please enter a file name. ex: npm start <filename>");
}
if (!fs.existsSync(`${fileName}.json`)) {
throw Error(`The file ${fileName}.json could not be found.`);
}
const jsonParsed = JSON.parse(fs.readFileSync(`${fileName}.json`, "utf8"));
const data = summarizeData(jsonParsed);
console.log(data);
} catch (error) {
throw Error(error);
}
I think it will be enough to unit test summarizeData function.
Something like this (using shouldJS for assertions):
const should = require('should');
const fileName = 'testData';
test('it summarize data properly', () => {
const jsonParsed = JSON.parse(fs.readFileSync(`${fileName}.json`, "utf8"));
const dataSummarized = summarizeData(jsonParsed);
dataSummarazied.something.should.be.equal(1); // TODO - add other assertions to cover all result
})