rewire: Doesn't work with ES6 consts

You get errors like this:

TypeError: Assignment to constant variable.
  at eval (eval at __set__ (my-module.js:73:19), <anonymous>:1:21)
  at Object.__set__ (my-module.js:73:5)
  at Context.<anonymous> (my-module-test.js:131:55)

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Reactions: 10
  • Comments: 28 (7 by maintainers)

Most upvoted comments

I can’t reproduce this issue. I can rewire const functions.

+1 for allowing rewire of const’s

Rewiring const is supported since 3.0.0

+1 for this. My workaround was using let instead of const to enable it to rewire.

@jhnns 4.0.0 here, this does not work.

main.js const { apiRoot, defaultPort } = require('config');

main.test.js

const myModule = rewire('myModule');

myModule.__set__('defaultPort', 123);

TypeError: Assignment to constant variable.

Do you have an example? I’m pretty sure that this can not work.

@erbridge @brenolf dcrockwell @dcrockwell For what it’s worth, proxyquire seems to work fine using ES6 consts.

I’ve yet to write some more complex tests with it but initial results are encouraging.

Still having this issue even with rewire 6.0.0, any fixes or workarounds?

Still having this issue even with rewire 5.0.0, any fixes or workarounds?

@jhnns I do have the same problem as @goyney 😦 I already have rewire 4.0.1

The only difference I have is that it’s not from destructuring.

Demo: index.js:

const myPromisifiedFunction = promisify(someFunct.ToPromisify)

index.test.js:

const myModule = rewire('../myModule')
const myStub = sinon.stub()
const myStubbedFunction = myModule.__set__('myPromisifiedFunction', myStub)

And what I get when running tests is: TypeError: Assignment to constant variable. at eval (eval at __set__ (index.js:159:5), <anonymous>:1:19) at Object.__set__ (index.js:159:5) at Object.<anonymous> (test/index.test.js:14:48)

+1 yet again!

I think it’s totally valid to change const objects, because const does not mean that the object itself is frozen (you could use Object.freeze() for that 😉 ). However, I would not change the code just for the test framework.

Riffing on what @kaktus42 was saying though, you can take advantage of the way JS const works for evil and profit in the case when it’s an object:

var r = rewire('./reducer');
const reduceAddAction = r.__get__('reduceAddAction');
reduceAddAction.method.to.stub = sinon.stub();

In this case you’re not reassigning the variable identifier, and you’re changing a referenced value, so it is possible, whether or not it’s a good idea or not is another thing entirely 😄

var r = rewire('./reducer');
const reduceAddAction = r.__get__('reduceAddAction');

Where reduceAddAction is a const function.

But maybe you were talking about overwriting?

you should check this out : https://mathiasbynens.be/notes/es6-const +1 for rewire