【问题标题】:Stubbing functions with Sinon and Promises使用 Sinon 和 Promises 存根函数
【发布时间】:2019-07-15 18:49:18
【问题描述】:

我有一些文件mainFile 使用方法helperMethod,这是一个在文件helperFile 中返回Promise 的方法。如何存根从helperMethod 返回的内容?

这是我目前所拥有的 -

帮助文件:

export function helperMethod() {return a Promise}
module.exports.helperMethod = helperMethod;

主文件:

import helperMethod from helperFile;

methodInMainFile() {console.log(helperMethod);}

主文件测试:

import methodInMainFile from mainFile;
import * as utils from helperFile;

sinon
  .stub(utils, 'helperMethod')
  .returns(Promise.resolve(madeUpResponse));
methodInMainFile();

上面的代码打印Promise { undefined }。如何让它打印Promise { madeUpResponse }?我不认为 helperMethod 实际上被调用(因为它不应该被调用),因为我在那里记录了一些东西并且它从未显示。

【问题讨论】:

    标签: javascript typescript sinon


    【解决方案1】:

    madeUpResponse 未定义。

    你必须定义madeUpResponse

    import methodInMainFile from mainFile;
    import * as utils from helperFile;
    
    const madeUpResponse = 'a string';
    
    sinon
      .stub(utils, 'helperMethod')
      .returns(Promise.resolve(madeUpResponse));
    methodInMainFile();
    

    【讨论】:

    • 我确实定义了madeUpResponse,只是觉得没有必要在代码sn-p中显示。
    【解决方案2】:

    您实际上是通过导入将 helperMethod 分配给它自己的变量,因此在导出对象上存根方法不会修改 mainFile 中的原始函数。下面的代码应该可以工作:

    主文件:

    import * as utils from './helperFile'
    
    methodInMainFile() {console.log(utils.helperMethod)}
    

    【讨论】:

      猜你喜欢
      • 2021-02-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2015-06-04
      • 1970-01-01
      相关资源
      最近更新 更多