Search code examples
javascriptnode.jsunit-testingmocha.jsassert

How can I write test to mock and handle JSON parsing error in nodejs


I am retrieving JSON data from a JSON type file for tests using the code below in my test.js file

var data;

  before(function(done) {
    data = JSON.parse(fs.readFileSync(process.cwd() + '/path/to/data.json', 'utf8'));
    done();
  });

How can I write a test to mock and test the JSON parsing error using assert or mocha? I want the test to confirm/assert that there was no error in parsing the JSON.


Solution

  • You should use the before hook only to do the setup of your tests, not to assert that the code you are trying to test is behaving as you expect (more information about the hooks and their use in the mocha documentation).

    To assert that the code you are trying to test is indeed behaving as you expect you should put your code inside an it.

    Taking this into account, you could read the raw data of your json file in the before hook (since this part is the setup of the test) and then write the parsing of the json string in the test:

    var rawData;
    
    before(function() {
        // No need to use 'done' since we are performing a synchronous task
        rawData = fs.readFileSync(process.cwd() + '/path/to/data.json', 'utf8');
    });
    
    it('should correctly parse the json', function() {
        var data = JSON.parse(rawData);
    
        // Your expectations about data would be placed here.
    });
    

    In order to do the expectations, you can use any assertion library you want and you should check that data has the properties and values that are present in your 'path/to/data.json' file.

    As an example, if you are using chai library for assertions and your data.json file has the contents:

    { key1: 'value1', key2: 'value2' }
    

    you could write the assertion:

    it('should correctly parse the json', function() {
        var data = JSON.parse(rawData);
    
        // Your expectations about data would be placed here.
        expect(data).to.deep.equal({ key1: 'value1', key2: 'value2' });
    });