samedi 27 mars 2021

How to test static javascript on web pages?

I want to test static JavaScript code, preferably with Jest which I use in web applications a lot.

I have a little (Django) project, that has some static JavaScript, lets say in:

./app/static/stuff.js

which contains some old style classes like this:

function Stuff() {
  this.do = function() {return 42};
}

Now, I want to test that code there without copying files and without having test files in the same directory and without the need to run that in the browser. So I created an npm module and added jest.

Now I added a test file

./__test__/stuff.test.js

with the following content

require('../app/static/stuff.js');

describe('Stuff', () => {
  if('should do stuff', () => {
    const stuff = new Stuff();
    expect(stuff.do()).toEqual(42);
  }
}

This does not work, because stuff.js is not a node module. So what I did to get this running in the browser (prod code) and tests itself is the following, which is quite hacky IMO but works:

function Stuff() {
  this.do = function() {return 42};
}

/* Hack to test this code, global is not available in the browser */
if (typeof global !== 'undefined') {
    global.Stuff = Stuff;
}

Is there a way to achieve the same without polluting my prod code?

Aucun commentaire:

Enregistrer un commentaire