title: Spy on or mock document.createElement using Jest
body: <p>I need to test some code that creates an element on document that is assigned a URL and then clicked. </p>
  
  <p>I am using Jest.</p>
  
  <pre><code>const link = document.createElement('a')
  </code></pre>
  
  <p>I gave up trying to mock document as I can't see a simple way to do it, although it would have been nice to mock out the click. </p>
  
  <p>I need to know that <code>createElement</code> happened, so I decided to create a spy:</p>
  
  <pre><code>jest.spyOn(document, 'createElement')
  </code></pre>
  
  <p>For some reason the spy is breaking the test and I get the same error that I got when trying to mock document:</p>
  
  <pre class="lang-sh prettyprint-override"><code>Error:  TypeError: Cannot set property 'href' of undefined
  </code></pre>
  
  <p>The code below the <code>document.createElement</code> is:</p>
  
  <pre><code>link.href = url
  </code></pre>
  
  <p>Any ideas?</p>