Search code examples
jsondojointern

Read local JSON files when dynamically creating functional tests in Intern


I am creating functional tests dynamically using Intern v4 and dojo 1.7. To accomplish this I am assigning registerSuite to a variable and attaching each test to the Tests property in registerSuite:

var registerSuite = intern.getInterface('object').registerSuite;
var assert = intern.getPlugin('chai').assert;

// ...........a bunch more code .........

registerSuite.tests['test_name'] = function() {

    // READ JSON FILE HERE
    var JSON = 'filename.json';

    // ....... a bunch more code ........
}

That part is working great. The challenge I am having is that I need to read information from a different JSON file for each test I am dynamically creating. I cannot seem to find a way to read a JSON file while the dojo javascript is running (I want to call it in the registerSuite.tests function where it says // READ JSON FILE HERE). I have tried dojo's xhr.get, node's fs, intern's this.remote.get, nothing seems to work.

I can get a static JSON file with define(['dojo/text!./generated_tests.json']) but this does not help me because there are an unknown number of JSON files with unknown filenames, so I don't have the information I would need to call them in the declare block.

Please let me know if my description is unclear. Any help would be greatly appreciated!


Solution

  • Since you're creating functional tests, they'll always run in Node, so you have access to the Node environment. That means you could do something like:

    var registerSuite = intern.getPlugin('interface.object').registerSuite;
    var assert = intern.getPlugin('chai').assert;
    
    var tests = {};
    tests['test_name'] = function () {
        var JSON = require('filename.json');
        // or require.nodeRequire('filename.json')
        // or JSON.parse(require('fs').readFileSync('filename.json', {
        //      encoding: 'utf8'
        //    }))
    }
    
    registerSuite('my suite', tests);
    

    Another thing to keep in mind is assigning values to registerSuite.tests won't (or shouldn't) actually do anything. You'll need to call registerSuite, passing it your suite name and tests object, to actually register tests.