How can I spy on a function that is being called from a reference to it inside an object ? I use Jasmine 2.5.2 as my testing framework and babel-plugin-rewire to rewire dependencies.
Take a look:
a.js
const map = {
a,
b,
c
};
function run(options) {
map[options.val]();
}
function a() {...}
function b() {...}
function c() {...}
a.spec.js
import { a, __RewireAPI__ as ARewireAPI } from './a';
describe('a', () => {
describe('run', () => {
const spy= jasmine.createSpy('spy').and.callFake(() => {
...
});
beforeEach(() => {
ARewireAPI.__Rewire__('b', spy);
});
afterEach(() => {
ARewireAPI.__ResetDependency__('b');
});
it('calls b()', () => {
a.run({val: 'b'}); // doesn't call the spy because what actually being called is the reference from the map object
});
});
});
Ok found a solution. Instead of rewiring the function rewire the map like so: