javascriptsalesforceaura-framework

Is there any way to import Javascript value that was not exported


I work with a system built in Salesforce, which includes Aura helper files. As described in the docs, each file consists of a single object literal in brackets, with functions as properties, e.g.

({
    someHelperMethod: function(a, b) {
        return a + b;
    }
})

I'd like to add unit tests for some of these functions, if possible without first editing the helper file, to ease adoption of JS unit tests in this context and minimise the risk of regressions to untested code. As far as I can see Salesforce does not have any built-in system for unit testing JS, so I would run these tests outside of Salesforce before deploying.

Is there any way that my test code that I will run in e.g. my node CLI can refer to and exercise someHelperMethod, or is it impossible since it was not exported? If it's impossible does anyone want to speculate on how Salesforce is accessing the object? Would I need to make a script to wrap the object in something like "export default [fileContent];" and write that out to a new JS file?


Solution

  • One way to solve this is to read the content of the file as a string and then write it into a separate file and add the export whiles writing to the file in the manner below:

    const fs = require('fs');
    
    // Read the original helper aura file file content
    const originalContent = fs.readFileSync('path/to/your/originalHelper.js', 'utf8');
    
    // Wrap the content and prepare it for export
    const wrappedContent = `module.exports = ${originalContent}`;
    
    // Write the wrapped content to a new file
    fs.writeFileSync('path/to/your/exportedHelper.js', wrappedContent);

    Afterwards you can write the test for this file instead.