speedskater / babel-plugin-rewire

A babel plugin adding the ability to rewire module dependencies. This enables to mock modules for testing purposes.
843 stars 90 forks source link

__Rewire__ interferes with Jasmine's this #193

Open 0nse opened 7 years ago

0nse commented 7 years ago

Hi all,

I'm trying to use Rewire together with Karma and Jasmine. Generally, it works well. However, as soon as I call __Rewire__, Jasmine's this becomes undefined. I use

"babel-plugin-rewire": "^1.1.0"

and import it as follows:

import { __Rewire__ as rewireAPI } from '../some-module';

When I'm assigning to this it works:

describe('Working test', () => {
      beforeEach(() => {
          this.variable = 'a value';
      });
      it('should be able to read the variable bound to userContext', () => {
          expect(this.variable).not.toBe(undefined);
          expect(this.variable).toBe('a value');
      });
});

However, if I rewire as follows:

describe('Failing test', () => {
    beforeEach(() => {
        this.variable = 'a value';
        rewireAPI.__Rewire__('functionToRewire', () => {});
    });
    it('should be able to read the variable bound to userContext', () => {
        expect(this.variable).not.toBe(undefined);
        expect(this.variable).toBe('a value');
    });

});

I get the following error: TypeError: undefined is not a function (evaluating '_get__('rewireAPI').__Rewire__('functionToRewire', function () {})')

I have seen #109 but I believe this issue is different as I can use Rewire perfectly fine as long as I refrain from using this.

You can find a minimal example here. The error is unrelated to Mocha, which I have just included for increasing readability of the test results.