Search code examples
javascriptunit-testingjestjsrevealing-module-pattern

How to write unit test for javascript revealing module pattern with Jest?


For example: my math_util.js is

var MathUtil = function(){
  function add(a,b){
    return a + b;
  }
  return {
    add: add
  };
}

I'll use Jest to test add(). So I'll write

test('add', ()=>{
  expect(MathUtil().add(1,1)).toBe(2);
});

But I get MathUtil is undefined or MathUtil() is not a function.

I also tried to use require() or import. But MathUtil doesn't have module.export or export.

So how to write unit test for javascript revealing module pattern with Jest?

Note: I've a project with all scripts written in revealing module pattern so convert all to ES2015 module may not be practical.


Solution

  • If you really want to test math_util.js exactly as it is written you can do this:

    // ---- math_util.test.js ----
    const fs = require('fs');
    const path = require('path');
    const vm = require('vm');
    
    const code = fs.readFileSync(path.join(__dirname, '/math_util.js'), 'utf-8');
    const MathUtil = vm.runInThisContext(code + '; MathUtil');
    
    test('add', ()=>{
      expect(MathUtil().add(1,1)).toBe(2);
    });
    

    ...but best practice would be to refactor the code into modules. For the revealing module pattern that should be a very straightforward process, just remove the outer wrapping function and returned object, and put export in front of anything that was in the returned object:

    // ---- math_utils.js ----
    export function add(a,b){
      return a + b;
    }
    
    
    // ---- math_utils.test.js ----
    import { add } from './math_utils';
    
    test('add', ()=>{
      expect(add(1,1)).toBe(2);
    });