使用 Mocha/Chai/Sinon 测试 document.createElement('a')

Testing document.createElement('a') with Mocha/Chai/Sinon

我正在尝试测试以下功能

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 的主机名匹配,我想要 return 那个容器。这种方法工作正常,但我不确定如何测试它,或者即使我应该这样做。我写了一个最初看起来像这样的测试:

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() 存根,那么我并没有真正测试任何东西,因为我每次都必须手动 return 主机名。

我应该测试这个功能吗?如果可以,我该如何测试?

首先,我认为您的测试用例看起来不错,我认为这绝对值得测试。将外部 objects/functions 存根以进行单元测试绝对没问题(在很多情况下都推荐这样做)。

我确实感到很困惑的是您使用 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 问题。

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

url = 'www.party.com'改为url = 'http://www.party.com'

后,本次测试将通过