title: How do I observe DOM changes in an Angular/Jasmine unit test?
body: <p>I have an Angular 8 application that uses Jasmine and Karma for unit testing.</p>
  
  <p>I have a fairly simple method that copies a string to the user's clipboard, and I am trying to unit test it. The method creates and destroys a temporary textarea as part of this copy process. I need to capture this textarea when it is created.</p>
  
  <pre><code>  copyToClipboard() {
      // Create a textarea to hold the string.
      const text = document.createElement('textarea');
      text.value = this.value;
      text.id = 'temporary_copy_area';
      document.body.appendChild(text);
  
      // Copy the contents of the textarea to the clipboard.
      text.select();
      document.execCommand("copy");
  
      // Clean up.
      document.body.removeChild(text);
    }
  </code></pre>
  
  <p>I created a <code>MutationObserver</code> in the test's <code>beforeEach</code> and I'm observing the document body. I disconnect in the <code>afterEach</code>.</p>
  
  <pre><code>  beforeEach(() =&gt; {
      observer = new MutationObserver((changes) =&gt; {
        console.log('observed an event');
      });
      observer.observe(document.body, {subtree: true, childList: true})
    });
  
    afterEach(() =&gt; {
      observer.disconnect();
    });
  </code></pre>
  
  <p>A simple test that just calls the SUT produces no log messages:</p>
  
  <pre><code>  it('should copy to the clipboard', () =&gt;
    {
      component.copyToClipboard();
    });
  </code></pre>
  
  <p>I know the code is executing, because the test text does wind up in the clipboard.</p>
  
  <p>If I comment out the <code>afterEach</code>, the observer stays connected and I'll see events if I manipulate the page.</p>
  
  <p>I tried commenting out the <code>removeChild</code> in the copy method, just in case the events were being suppressed because they canceled out. That didn't help.</p>