【问题标题】:Testing document.createElement('a') with Mocha/Chai/Sinon用 Mocha/Chai/Sinon 测试 document.createElement('a')
【发布时间】:2018-04-08 10:24:02
【问题描述】:

我正在尝试测试以下功能

export const checkForDuplicateUrl = (containers, url) => {
  let a = document.createElement('a')
  a.href = url
  const urlHostName = a.hostname

  return containers.find((container) => {
    let b = document.createElement('a')
    b.href = container.url
    return urlHostName === b.hostname
  })
}

这个函数接受一个containers 的数组和一个给定的url。如果 url 的主机名与任何个人 containers 的主机名匹配,我想返回该容器。这种方法效果很好,但我不确定如何测试它,或者即使我应该这样做。我写了一个测试,最初看起来像这样:

describe('#checkForDuplicateUrl', () => {    
    const containers = [
      { id: 4, url: 'https://www.party.com'},
      { id: 5, url: 'elainebenes.com'}
    ]
    let url
    describe('when there is a duplicate container and the passed in are the same', () => {
      url = 'www.party.com'
      it('returns the container', () => {
        expect(checkForDuplicateUrl(containers, url).id).to.equal(4)
      })
    })
    describe('when there is a duplicate container and the passed in are the same hostname but one lacks www', () => {
      url = 'party.com'
      it('returns the container', () => {
        expect(checkForDuplicateUrl(containers, url).id).to.equal(4)
      })
    })
    describe('when there is a duplicate container and the passed in are the same hostname but one has https', () => {
      url = 'www.party.com'
      it('returns the container', () => {
        expect(checkForDuplicateUrl(containers, url).id).to.equal(4)
      })
    })
  })

问题是,当我在我的测试环境中运行它时,document.createElement('a') 总是将localhost 作为它的主机名,所以我传入什么并不重要。

如果我尝试用 sinon 将 document.createElement() 存根,那么我并没有真正测试任何东西,因为我每次都必须手动返回主机名。

我应该测试这个功能吗?如果是这样,我应该如何测试它?

【问题讨论】:

    标签: javascript unit-testing mocha.js sinon chai


    【解决方案1】:

    首先,我认为您的测试用例看起来不错,我认为这绝对是值得测试的东西。将外部对象/函数存根用于单元测试是绝对好的(并且在很多情况下推荐)。

    我发现非常令人困惑的是您使用 document.createElement() 从 url 获取主机名。我会尝试使用像url-parse 这样的专用库。

    var URL = require('url-parse');
    var url = new URL('http://www.google.com')
    console.log(url.hostname); // 'google'
    

    我不完全确定您要传递给 checkForDuplicateUrl() 的内容,但我认为这可以解决 localhost 问题。

    【讨论】:

      【解决方案2】:

      这里的问题与我传递给函数的url 没有以http 开头有关。当您尝试在没有httpa 标签上设置href 时,a 标签只会抓取您当前的位置,在本例中为http://localhost

      url = 'www.party.com'更改为url = 'http://www.party.com'后,此测试将通过

      【讨论】:

        猜你喜欢
        • 2015-12-01
        • 2023-04-11
        • 1970-01-01
        • 2018-11-05
        • 2023-03-22
        • 2017-10-08
        • 2019-02-03
        • 2017-10-23
        • 1970-01-01
        相关资源
        最近更新 更多