简体   繁体   English

茉莉花和通天塔重传间谍的参考方法

[英]Jasmine and babel rewire spy on a referenced method

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. 我使用Jasmine 2.5.2作为我的测试框架,并使用babel-plugin-rewire重新连接依赖项。

Take a look: 看一看:

a.js a.js

const map = {
 a,
 b,
 c
};
function run(options)  {
 map[options.val]();
}
function a() {...}
function b() {...}
function c() {...}

a.spec.js 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: 不必重新布线该函数,而是重新布线地图,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM