控制台日志 sinon.spy() 显示 [Function] 而不是间谍的内容

Console logging sinon.spy() shows [Function] instead of the contents of the spy

我试图查看 sinon.spy() 的输出,但是当我执行 console.log( res.render ) 时,当我 运行 测试时,我只在控制台中看到 [Function]

const should = require( 'chai' ).should()
const sinon = require( 'sinon' )

const getIndex = ( req, res ) => {
  res.render( 'index' )
}

describe( 'getIndex', function () {
  it( 'should render index', function () {
    let req = {}
    let res = {
      render: sinon.spy()
    }

    getIndex( req, res )

    console.log( res.render ) // Expecting all properties from sinon.spy()
    res.render.firstCall.args[ 0 ]
      .should
      .equal( 'index' )
  } )
} )

编辑: 我期待看到 sinon.spy() 中可用的所有属性。例如,firstCall.args[ 0 ] 属性 但我想查看所有属性。我知道它们列在 https://sinonjs.org/releases/v7.4.2/spies/ 但我希望一次看到所有属性,因为我试图更好地了解 sinon 如何进行测试。

  • 当您点击 function 部分时(如果您至少在 chrome 开发控制台中),它将向您显示功能代码的内容,而不是其结果。
  • 这是因为 res.render 不是字符串或数字或其他任何东西,它是一个函数。
  • 因此,我们需要一些方法来记录 res.render 的输出。
  • 如果我们调用 res.render 并将其传递给它必要的参数,我们将得到 res.render() 的输出。
  • TL;DR 我会尝试 console.log(res.render("index")) 而不是 console.log(res.render)

TL;DR

  • 间谍是函数。
  • 开发工具控制台或 watch 概览不显示函数对象的属性。

间谍

间谍是函数,因为它们应该用作函数代理或替换对象上的函数以跟踪对它们的调用。间谍将在内部跟踪调用以允许程序化检查。

Javascript

您可能不知道 Javascript 函数也是对象。

In JavaScript, functions are first-class objects, because they can have properties and methods just like any other object. What distinguishes them from other objects is that functions can be called. In brief, they are Function objects.

来源:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions

函数可以有属性,并且可以像在 "normal" 对象上一样定义或配置属性。

间谍不通过调试器或 console.log() 在检查器中显示属性的原因是,开发工具知道它的功能并且功能是这样显示的。

开发工具

开发工具显然假定 Function 对象(通常)没有特殊属性,因此不会枚举它们。

您也可以通过基本功能观察到这一点。在控制台中输入:

var f = function() { }
f.foo = 42;
f; // The property won't be printed

不过,您可以在断点处停止时在调试器中检查间谍对象。您可以在 "Source" 选项卡中添加对 "Watch" 面板的引用。然后您可以打开函数对象并检查属性。

完成之前的实验后,您确实可以通过为 f.

添加监视表达式来检查函数

正在检查的诗乃间谍对象: