Chanh
Chanh

Reputation: 43

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.

Upvotes: 4

Views: 806

Answers (2)

thomasaull
thomasaull

Reputation: 31

You can use babel-plugin-rewire for this. Check this post: https://www.samanthaming.com/journal/2-testing-non-exported-functions/

Upvotes: 0

Brian Adams
Brian Adams

Reputation: 45860

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);
});

Upvotes: 3

Related Questions