如何监视从对象内部引用调用的函数? 我使用Jasmine 2.5.2作为我的测试框架,使用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
});
});
});
答案 0 :(得分:0)
好的找到了解决方案。 而不是重新布线功能重新映射地图如下:
beforeEach(() => {
ARewireAPI.__Rewire__('map', {b: spy});
});
afterEach(() => {
ARewireAPI.__ResetDependency__('map');
});