How to replace file data

Viewed 40

In my folder I have app.js, app.test.js and config.json

My config.json is filled with the correct information but I want to test the negative scenario, when the file does not contain any data data.length === 0

How can I replace the config.json for the test without actually replacing the file correct data?

const fileData = fs.readFileSync(path.resolve(__dirname, './config.json'));
const data = JSON.parse(fileData);

if (!data || data.length === 0) {
  console.error('data is required!');
  return;
}

   ... 



// Test

it('#lambdaHandler should validate data configuration file', async() => {
  const response = await app.myFunction();
});

1 Answers

You can try a simple solution that would involve duplicating the file and emptying it or simply creating a new one from scratch and doing the text on the latter.

Anyway, be careful, the JSON.parse function can throw an exception. It correctly handles the exception that might be created with a try/catch block (do it now). For example, if you parse an empty file it should return error since an empty string is not eligible for JSON.parse.

Below is an implementation I made to test that it worked

const fs = require( "fs");
const path = require( "path")


const fileData = fs.readFileSync(path.resolve(__dirname, './config.json'));


try{
    const data = JSON.parse(fileData);

    if (Object.keys(data).length === 0) {
        console.error('Data is required! Please provide json with data');
    }else{
        console.error('Yes! Json loaded correctly with data');
        console.log(data)
    }

}catch(error){
    console.log("Parsing json operation, failed");
}

Related