【问题标题】:JavaScript Unit Test for custom function自定义函数的 JavaScript 单元测试
【发布时间】:2013-07-23 07:27:30
【问题描述】:
function testRef() {
  if(document.referrer) {
     return /isgoogle/.test(document.referrer)
  }
  return false;
}

让我们假设一个如上的函数。为这样的功能编写单元测试的好方法是什么[因为我们不能覆盖 document.referrer]。有没有其他好的方法来测试这样的场景,比如在 javascript 中的 iframe、referrer、位置等?我目前正在使用非常好的 qunit。但未能在此类场景的框架中找到出路。

【问题讨论】:

  • 致反对票:减少反对票的理由是浪费时间..

标签: javascript unit-testing qunit


【解决方案1】:

最简单的方法是把算法从依赖中分离出来:

function testRefImpl(doc) {
  if(doc.referrer) {
     return /isgoogle/.test(doc.referrer)
  }
  return false;
}

// unit test
assertFalse(testRefImpl({referer: "abc"}))
assertTrue(testRefImpl({referer: "isgoogle"}))

// dependency declaration module
// so primitive, that there is no point to unit test it.
function testRef() {
  return testRefImpl(document)
}

【讨论】:

    猜你喜欢
    • 2011-11-05
    • 2018-02-25
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多