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

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

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am trying to test the following function

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
  })
}

This function takes in an array of containers and a given url. Should the hostname of the url match the hostname of any of the individual containers, I want to return that container. This method works fine, but I’m not sure how to test this, or indeed even if I should. I wrote a test that initially looked like this:

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)
      })
    })
  })

The problem is, that when I run this in my testing environment, document.createElement('a') is always going to have localhost as it’s hostname, so it doesn’t really matter what I pass in.

If I try to stub the document.createElement() out with sinon, then I’m not really testing anything since I will have to manually return the hostname every time.

Should I even test this function? If so, how should I test it?

Answers: