Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using rewire to test node ES6 module - function not defined

Tags:

EDIT : This was answered pretty quickly by someone pointing to something obvious in the rewire documentation. Note that I wrapped my modules in IIFEs because I was trying to get node to stop complaining about block scoped declarations outside of strict mode. Instead of using IIFEs (with strict mode), the easier way is just to use the --use-strict flag on your node command:

node --use-strict app.js

that way you can use ES6 in your code as normal and they will still be accessible by rewire. Hooray!


I am trying to test my node ES6 application. More specifically, I am trying to test a function in a module that isn't exported from a module. Currently, I cannot even get that function to be defined in my test. I am trying to use rewire to test this.

I'm not sure if this might a problem with strict mode or using ES6, but I cannot seem to find any hints to solutions online :(

Any help would be appreciated!

Here is my module:

//myModule.js
(function(){
  'use strict';

  let myFunction = () => {
    return 'hello';
  };

})();

And here is my test:

//myModule.spec.js
(function(){
  'use strict';

  let rewire = require('rewire');
  let myModule = rewire('./myModule.js');

  describe('app', () => {

    it('should do something', () => {

      let func = myModule.__get__('myFunction');
      expect(func).toBeDefined();

    });


  });

})();

And this is the output I get from running jasmine-node on the directory:

Failures:

  1) app should do something
   Message:
     ReferenceError: myFunction is not defined
   Stacktrace:
     ReferenceError: myFunction is not defined
like image 357
dafyddPrys Avatar asked Jun 08 '16 08:06

dafyddPrys


1 Answers

Those IIFE's you're wrapping your code with are causing the problem. It's even mentioned in the fine manual:

Variables inside functions can not be changed by rewire

like image 135
robertklep Avatar answered Oct 03 '22 18:10

robertklep