How to refactor JS legacy to implement Unit Tests?

2

I have a WordPress site with lots of JS files that were not structured to be tested - they were not written as modules that can be imported nor is there a app.js that loads all of them as a framework.

The files are only compiled and mined for use on the site, and I want to start rephrasing little by little, as I go about doing site maintenance, adding bug-solved tests and new features.

All files have a structure similar to:

( function( window ) {
    'use strict';

    var document = window.document;

    var objeto = { 
        params : {
            // etc
        },
        init: function() {
            // etc
        },
        outroMetodo: function() {
            // etc
        }

    }

    objeto.init();
} )(this);

I was suggested using Jest and the setup was quite simple - the testing environment is ready - but I do not know how to load the files that need to be tested. My current setting in package.json is this:

{
  "scripts": {
    "test": "jest"
  },
  "jest": {
    "verbose": true,
    "testMatch": [
      "<rootDir>/tests/jest/**/*.test.js"
    ]
  }
}

I imagine you need to refactor the files somehow so you can load them into Jest before running the tests, but what would be the simplest way to allow this integration without rewriting the features? I tried to use the settings setupFiles and setupTestFrameworkScriptFile but since I do not have a single setup file it seems to me that it is not the ideal option.

Is there a way to include the file to be tested at the beginning of each test to test the methods?

include( '/arquivo.js' ); // pseudocodigo

describe("Testes para arquivo.js", function() {
    it("testes do metodo X", function() {
        expect(true).toBe(true);
    });
});
    
asked by anonymous 27.06.2018 / 14:47

0 answers