using rewire to test node ES6 module - function not defined

daf*_*rys 5 node.js jasmine ecmascript-6

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
Run Code Online (Sandbox Code Playgroud)

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

})();
Run Code Online (Sandbox Code Playgroud)

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

    });


  });

})();
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

rob*_*lep 4

您用来包装代码的 IIFE会导致问题。甚至在精美的手册中也提到过:

函数内的变量不能通过重新连线来更改