I am new with Jest and I need to test a node.js, express application with Jest and I would really appreciate your help with this:
My app.js file save data into a JSON file that will be used in task10.js
My task10.js file reads the local JSON file sending a XMLHttpRequest() then uses the data received through the whole file. (I have tried a fetch method in task10.js and get an error fetch is not defined, tried fs read and get an error: required is not defined)and still can’t get around it. The elements return values of undefined.
How would I be able to get the exported elements from task10.js and test them in Jest after by having the following:
TASK10.JS
'use strict';
const readTextFile= function(file, callback) {
var rawFile = new XMLHttpRequest();
rawFile.overrideMimeType("colors1/json");
rawFile.open("GET", file, true);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4 && rawFile.status == "200") {
callback(rawFile.responseText);
}
}
rawFile.send(null);
}
//usage:
readTextFile("public/colors1.json", function(text){
var data = JSON.parse(text);
let colors = [
data.red,
data.blue,
data.green,
data.yellow,
data.orange,
data.pink,
];
let maxRounds= 6;
module.exports= {colors,maxRounds};
});
TASK10.TEST.JS
test('js file exports', () => {
let {colors,maxRounds} = require('../task10');
//examples - I will have to run different tests
expect(typeof colors).not.toBe('undefined');
expect(typeof maxRounds).not.toBe('undefined');
});
});
APP.JS
//function that creates file, write colors json elems on it and close file
function saveToFile(data, outFile) {
var writeFile;
try {
//test a block of code for errors.
writeFile = fs.openSync(outFile, "w");
fs.writeSync(writeFile, data);
fs.close(writeFile);
console.log('saved')
} catch (err) {
// handle the error.
console.log(
"\n[" + "] Error: Unable to save " + outFile + "\n" + err + "\n"
);
}
}
//stringify data convert data to JSON string
let data = JSON.stringify(colors);
app.get("/task10", function (req, res) {
//invoke function to handle file colors1.json
saveToFile(data, "colors1.json");
//write file that we will read via our task 10.js
res.render("task10");
});
THANKS A LOT IN ADVANCE!!