Jasmine 和 babel 在引用的方法上重新连接 spy

Jasmine and babel rewire spy on a referenced method

如何监视从对象内部对它的引用调用的函数? 我使用 Jasmine 2.5.2 as my testing framework and babel-plugin-rewire 重新连接依赖项。

看一看:

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
    });
  });
});

好的,找到解决办法了。 而不是像这样重新连接函数重新连接地图:

beforeEach(() => {
      ARewireAPI.__Rewire__('map', {b: spy});
    });
    afterEach(() => {
      ARewireAPI.__ResetDependency__('map');
    });