SpyOn单独导出ES6功能 [英] SpyOn individually exported ES6 functions

查看:161
本文介绍了SpyOn单独导出ES6功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

tl; dr:


  1. 我使用 Jasmine ;

  2. 我想从同一个
    测试 aaa 函数,该函数调用 bbb 模块;

  3. 我想监视 bbb ,但最终 aaa 称为
    原始 bbb 功能,不是间谍;

  1. I use Jasmine;
  2. I want to test aaa function which called bbb from the same module;
  3. I want to spy on bbb, but eventually aaa called the original bbb 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?

PS 我不想更改模块的代码,因为在这种情况下我将不得不改变项目中的大量代码。我需要一个通用的测试解决方案。

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.

推荐答案

即使思想不是同一个框架,也有一个相关的问题可以解释为什么这不起作用:如何在同一模块中模拟函数使用开玩笑。基本上你不能访问函数的这个固定引用,而是明确它与模块上下文中的函数相同。

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.

我知道这不符合您在问题中发布的约束,但它很明显,使用间谍无法实现您想要实现的目标。

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功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆