I am trying to get some unit tests set up using Mocha.js and Chai, one of the tests I am trying to make is to check to see if a json file has been created after a class in an external file is called.
const chai = require('chai');
chai.use(require('chai-json'));
const DataHandler = require('../handler');
const expect = require('chai').expect;
const path = require('path')
const handler = new DataHandler();
describe('#json handling', function(){
it('should create a testData.json file', function(){
const json = path.basename('../testData.json');
expect(json).to.be.a.jsonFile();
})
})
The tests are successful if I run them a second time as the testData.json file is created after the first tests are completed. This however shouldn't be the case and the json file should be created even before the test is run when new DataHandler
is initialised
This is the first part of my DataHandler class that creates/updates the json file is as follows
class DataHandler{
constructor(){
if(this.shouldUpdate()) {this.update()};
}
shouldUpdate(){
if(!fs.existsSync("testData.json")) {return true};
const file = fs.readFileSync("testData.json");
const parsed = JSON.parse(file)
const oldDT = Date.parse(parsed['updated_date']);
const dateDifference = Date.now() - oldDT;
const minutes = Math.floor(dateDifference / 60000);
if (minutes > 2) {return true};
}
update(){
request("http://someurl.com/data.json", function (error, response, body) {
if (!error && response.statusCode == 200) {
const parsedJSON = JSON.parse(body);
parsedJSON['updated_date'] = new Date();
const json = JSON.stringify(parsedJSON);
fs.writeFileSync("testData.json", json);
}
})
}
}