Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to test with Jest an old non-module JavaScript?

Consider an old project (very common in my opinion):

static/
   js/
      file1.js
      file2.js
      ....
   index.html

index.html

...
<script type="text/javascript" src="js/file1.js"></script>
<script type="text/javascript" src="js/file2.js"></script>
...

file1.js:

// publicly exposed class/function
var Person = function(name, age) {
    this.name = name;
    this.age= age;
}
Person.prototype.getName = function() {
    return this.name + '(' + this.age   + ')'
}

file2.js:

// publicly exposed function
var createPerson = function(name) {
    return new Person(name);
}

The contents of file1.js and file2.js are just dummy for showing the problem.

Is it possible to write a test of the form?:

file2.test.js:

// require('./file2');
// require('./file2');
test('create', () => {
    let person = createPerson('Tester', 40);
    expect(person.getName()).toBe('Tester (40)');
});

I tried searching for babel plugins that transform window/global attached variables to module exports, tried also with the Jest 'setupFiles' config property. Maybe Jest is not ment for such cases, just want to not look for another test framework as I already use Jest for other modern modular apps.

If not how to test such old application JavaScript - I know I can use Jasmine or Mocha and run the tests in the browser, but would like this to happen in Node environment, so that it could be finally handled with CI for instance?

like image 627
Rumen Neshev Avatar asked Oct 16 '25 10:10

Rumen Neshev


1 Answers

You will need to merge the scope of the files as part of the current context - e.g. by synchronously loading and dangerously evaling the sources into the current test file - making anything imported in such a manner available there for testing (including potential unexpected conflicts and side-effects - as you would in a non-modular global window context).

const script = (url) => {
    const { protocol } = new URL(url, 'file://');
    switch (protocol) {
        case 'file:':
            return require('fs').readFileSync(`${process.cwd()}/${url}`, 'UTF8');
        case 'http:':
        case 'https:':
            return String(require('child_process').execSync(`wget -O - -o /dev/null '${url}'`))
        default:
            throw new Error('unsupported protocol');
    }
};

eval(script('js/file1.js'));
eval(script('js/file2.js'));

// ... tests 
like image 63
Ian Carter Avatar answered Oct 19 '25 01:10

Ian Carter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!