Home > Back-end >  How do I test this very old legacy Javascript module without rewriting it?
How do I test this very old legacy Javascript module without rewriting it?

Time:03-27

How do I load and instantiate this legacy javascript module for testing, without modifying it?

The legacy module (foo.js):

var Smurf = {};

Smurf.Foo = function() {};
Smurf.Foo.prototype = {
    bar: function() {
        return 'baz';
    }
};

The legacy front-end (working):

<script src="foo.js"></script>

<script type="text/javascript">
$(function(){
    var foo = new Smurf.Foo();
    var qux = foo.bar();
});
</script>

The new test (failing):

const something = require('foo.js');
var foo = new Smurf.Foo();

Result:

Error: Failed to load file test/test.js
ReferenceError: Smurf is not defined

CodePudding user response:

What you can do is include both the file you need to test and the file with the tests in a new html file. This way, first the file that needs testing is loaded and everything it has in it can be tested in the test file.

test.hml:

<html>
    <head>
        <script scr="foo.js">
        <script src="test.js">
    </head>
</html>

Every time you need to run a test, open test.html in a browser. Of course you need to rewrite the test file so it shows some output, either in the console or in the html itself.

CodePudding user response:

The legacy module isn't a CommonJS module, therefore require() will not work. I recommend reading through this post to understand how require() works.

The short answer would be - you cannot "require()" foo.js and access Smurf unless the foo.js is exporting it (using something like module.exports).

Since you mentioned not wanting to rewrite the legacy code, I'd like to point you to this neat trick to Import non-ESM libraries in ES Modules, with client-side vanilla JS

  • Related