2

I'm testing in a ES6 babel-node environment. I want to mock a method thats used inside of the method I'm importing. The challenging part seems to be that the method I want to mock is imported into the file where the method I want to test resides. I've explored proxyquire, babel-plugin-rewire but I can't seem to get them to work on methods imported inside of other imports. From reading through various github issues I get the feeling that this might be a known limitation/frustration. Is this not possible or am I missing something?

No errors are produced when using proxyquire or babel-plugin-rewire. The method just doesn't get mocked out and it returns the methods normal value.

Here's a generic example of the import situation.

// serviceLayer.js

getSomething(){
  return 'something';
}


// actionCreator.js

import { getSomething } from './serviceLayer.js';

requestSomething(){
  return getSomething();  <------- This is what I want to mock
}


// actionCreator.test.js

import test from 'tape';
import {requestSomething} from 'actionCreator.js'

test('should return the mock' , (t) => {
  t.equal(requestSomething(), 'something else');
});
mpls423
  • 63
  • 1
  • 2
  • 8
  • If you can modify the your tested file, you can use dependency injection techniques to solve your problem. Some of them are described in http://jasonpolites.github.io/tao-of-testing/ch3-1.1.html . You can do this by passing the getSomething function as an argument of requestSomethign for example. – Frank Bessou May 04 '17 at 23:28
  • @FrankBessou Yeah I realize I could pass it in as an argument. It wouldn't be terrible if thats necessary but I was really hoping to not have to add additional arguments to all of my methods. Thanks for looking and the suggestion/link. – mpls423 May 05 '17 at 13:13
  • If all your methods need the same function you can still pass this function to the class constructor. – Frank Bessou May 05 '17 at 13:20

1 Answers1

2

I'm answering my own question here... Turns out I was just using babel-plugin-rewire incorrectly. Here's an example of how I'm using it now with successful results.

  // serviceLayer.js

  export const getSomething = () => {
    return 'something';
  }


  // actionCreator.js

  import { getSomething } from './serviceLayer.js';

  export const requestSomething = () => {
    return getSomething();  <------- This is what I want to mock
  }


  // actionCreator.test.js

  import test from 'tape';
  import { requestSomething, __RewireApi__ } from 'actionCreator.js'
  __RewireApi__.Rewire('getSomething' , () => {
    return 'something else''
  });

  test('should return the mock' , (t) => {
    t.equal(requestSomething(), 'something else');
  });
mpls423
  • 63
  • 1
  • 2
  • 8