SpyOn individually exported ES6 functions(SpyOn 单独导出的 ES6 函数)
问题描述
tl;博士:
- 我用茉莉花;
- 我想测试调用
bbb
的aaa
函数模块; - 我想监视
bbb
,但最终aaa
调用了原bbb
函数,不是spy;
- I use Jasmine;
- I want to test
aaa
function which calledbbb
from the same module; - I want to spy on
bbb
, but eventuallyaaa
called the originalbbb
function, not a spy;
如何强制 aaa
调用间谍?
How can I force aaa
to call the spy?
模块:
export function aaa() {
return bbb();
}
export function bbb() {
return 222;
}
测试:
import * as util from 'my-module';
describe('aaa test', () => {
let bbbSpy: Spy;
beforeEach(() => {
bbbSpy = spyOn(util, 'bbb');
});
it('should return SPYED', () => {
bbbSpy.and.returnValue('SPYED!!');
const result = util.aaa();
expect(result).toEqual('SPYED!!'); // Doesn't work - still 222
});
});
所以,这基本上是行不通的.谁能帮帮我?
So, basically that doesn't work. Can anyone help me please?
P.S.我不想更改模块的代码,因为在这种情况下我将不得不更改项目中的大量代码.我需要一个通用的测试解决方案.
P.S. I don't want to change the module's code, because in that case I'll have to change tons of code in the project. I need a general solution for tests.
推荐答案
即使认为不是同一个框架,有一个相关的问题告诉你为什么这不起作用:如何使用 jest 在同一模块中模拟函数.基本上,您将无法访问该函数的固定引用,而是明确表示该函数与模块上下文中的函数相同.
Even thought is not the same framework, there is a related question that gives you why this doesnt work: How to mock functions in the same module using jest. Basically you wont be able to access this fixed reference of the function and instead make clear that is the same function as in the context of the module.
我知道这不满足您在问题中发布的约束,但很明显,您想要实现的目标是无法通过使用 spy.
I know this doesn't satisfy the constraint that you post in your question, but it just makes obvious that what you want to achieve is not possible by using spy.
使用 JavaScript,没有办法交换对某些东西的引用.您不能换出模块内部的函数.当您尝试在示例中使用 spyOn.and.returnValue 覆盖 bbb 时,您只是在修改测试中的本地绑定 bbb,但它对您其他文件中的 bbb 绑定没有影响.
With JavaScript, there is no way to swap out references to something. You cannot swap out a function that is internal to a module. When you try to overwrite bbb with spyOn.and.returnValue in your example, you are just modifying the local binding bbb in your test but it has no effect on the bbb binding in your other file.
这篇关于SpyOn 单独导出的 ES6 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SpyOn 单独导出的 ES6 函数
基础教程推荐
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 动态更新多个选择框 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01