Javascript 测试存根全局变量函数

Javascript testing stub global variable function

我正在为 React 应用程序编写一些单元测试。

在页眉中,'mixpanel' 跟踪库添加在 <script> 标记之间,如此处所述:https://mixpanel.com/help/reference/javascript。根据他们的文档,"The snippet provides a global variable named mixpanel that you can use to send data to the Mixpanel API."

在React组件的代码中,Mixpanel的track函数是这样调用的:

  showModal: function(evt) {
    evt.preventDefault()
    var modal = this.refs.modal
    modal.showModal()
    mixpanel.track("Login button clicked")
  }

但是在测试中,出现了mixpanel.track没有定义的错误(调用showModal时)。我已将测试环境设置为使用 testdom,如下所述:http://willcodefor.beer/react-testing-with-mocha-chai-sinon-and-gulp/ and here http://www.hammerlab.org/2015/02/14/testing-react-web-apps-with-mocha/.

我相信我需要模拟 track 方法至少存在,以便在测试中不会抛出错误。这是否正确,最好的方法是什么?

您可以创建全局对象来模拟它

mixpanel = {
  track : fucntion(){}
}