如何在javascript全局命名空间中存根/模拟一个函数 [英] How can I stub/mock a function in the javascript global namespace

查看:63
本文介绍了如何在javascript全局命名空间中存根/模拟一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在测试期间存根/模拟/覆盖函数调用,这会将日志写入数据库。

I'm trying to stub/mock/override a function call during testing which writes a log to a DB.

function logit(msg) {
  writeMessageToDb(msg);
}

function tryingToTestThisFunction(){
  var error = processSomething();
  if (error) {
    logit(error);
  }
}

我想 logit ()在测试期间简单地打印到控制台...并执行 isTesting()if / else阻止在<$ c内$ c> logit()函数不是一个选项。

I'd like logit() to simply print to the console during testing...and doing a "isTesting()" if/else block inside the logit() function is not an option.

这是否可行,不包括一些额外的模拟框架。我目前正在使用 JsTestDriver 进行单元测试,并且没有机会评估任何模拟框架。目前理想的解决方案是在没有其他框架的情况下处理这个问题。

Is this possible without including some additional mocking framework. I'm currently using JsTestDriver for unit testing and have not had a chance to evaluate any mocking frameworks. An ideal solution at the moment would be to handle this without another framework.

推荐答案

我使用Jasmine和Sinon.js(使用Coffeescript),这是我如何删除 confirm()方法,例如,只返回true。

I use Jasmine and Sinon.js (using Coffeescript), here's how I stub out the confirm() method to, for example, just return true.

beforeEach ->
  @confirmStub = sinon.stub(window, 'confirm')
  @confirmStub.returns(true)

afterEach ->
  @confirmStub.restore()

这篇关于如何在javascript全局命名空间中存根/模拟一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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