SpyOn 单独导出的 ES6 函数

SpyOn individually exported ES6 functions(SpyOn 单独导出的 ES6 函数)

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

问题描述

tl;博士:

  1. 我用茉莉花
  2. 我想测试调用 bbbaaa 函数模块;
  3. 我想监视 bbb,但最终 aaa 调用了原bbb函数,不是spy;
  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?

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 函数

基础教程推荐