speedskater / babel-plugin-rewire

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

Unable to rewire multiple values #179

Closed tracker1 closed 7 years ago

tracker1 commented 7 years ago

code under test

import bluebird from 'bluebird';
import createRedisPool from 'redis-connection-pool';
import config from '../../config';

let client = null;

export default function getClient() {
  console.log('bluebird', bluebird);
  console.log('createRedisPool', createRedisPool);
  console.log('config', config);

  // client already exists, return it
  if (client) return client;
  client = createRedisPool('default', config.redis);
  bluebird.promisifyAll(client);
  return client;
}

test case

/* eslint-disable */

import sit from './get-client';

describe('shared/redis/get-client', () => {
  let bb, cfg, c, rp;

  beforeEach(() => {
    bb = {
      promisifyAll: sinon.stub().returnsArg(0),
    };
    cfg = {
      redis: {},
    }
    c = {};
    rp = sinon.stub().returns(c);

    sit.__Rewire__('bluebird', bb);
    sit.__Rewire__('redis-connection-pool', rp);
    sit.__Rewire__('config', cfg);
  });

  afterEach(() => {
    sit.__ResetDependency__('bluebird');
    sit.__ResetDependency__('redis-connection-pool');
    sit.__ResetDependency__('config');
  });

  it('will create a client pool if needed', () => {
    sit.__Rewire__('client', null);
    const result = sit();
    //expect(rp).to.have.been.calledWith('default', cfg.redis);
    //expect(bb.promisifyAll).to.have.been.calledWith(c);
    expect(result).to.equal(c);
  });

  it('will reuse a client pool if needed', () => {
    sit.__Rewire__('client', c);
    const result = sit();
    expect(rp).to.have.not.been.called;
    expect(result).to.equal(c);
  });
});

output:

bluebird function Promise(executor) {
  ...
}
createRedisPool function (uid, cfg) {
  ...
}
config { redis: {} }

The config is being set, but bluebird and createRedisPool are not.

tracker1 commented 7 years ago

Okay, PEBKAC issue, my bad on using the package name, not the variable.