【发布时间】: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