Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
How do I test this very old legacy Javascript module without rewriting it?

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
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

In NodeJS, you can use the vm module https://nodejs.org/api/vm.html#vmruninthiscontextcode-options.

const { runInThisContext } = require('vm');
const { readFileSync } = require("fs");
function legacyRequire(path) { return runInThisContext(readFileSync(path)); }

var something = legacyRequire('./foo.js');
var foo = new Smurf.Foo();
console.assert(foo.bar() === 'baz');

enter image description here

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!