0

I have a simple app that I am trying to write a unit test for. I want to unit test the help button in the sample code below to make sure the loading status becomes an empty string. However, I cannot figure out how to get a fake DOM working. I have tried jsdom, jsdomifiy, jsdom-global, etc. I always end up with appStatus being undefined, then I can't set the innerHTML property. I am trying to use karma and mocha, but if there is a better way please let me know. I don't really have a package.json to share because I have tried so many things.

var appStatus = document.getElementById('appStatus');
appStatus.innerHTML = 'Loading your app...';


function help() {
console.log('help clicked');
appStatus.innerHTML = '';
}
<!DOCTYPE html>
<html>
  <head>
    <title>App</title>
  </head>
  <body>
    <span id="appStatus"></span>
    <button onclick="help()">Help</button>
  </body>
</html>
  • `.getElementById()` either returns the element with the given id or `null` but never `undefined` – Andreas Oct 04 '19 at 15:37
  • `var appStatus = document.getElementById('appStatus');` has to be executed _after_ the element is available in the DOM -> [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – Andreas Oct 04 '19 at 15:40
  • Yes sorry, i meant appStatus.innerHTML is undefined. From a unit test perspective, how can I make sure the DOM is available first? – epatmalnieks Oct 04 '19 at 15:45
  • _"appStatus.innerHTML is `undefined`"_ that would only be possible if `.getElementById()` would return some strange non-standard [Element](https://developer.mozilla.org/en-US/docs/Web/API/Element). – Andreas Oct 04 '19 at 15:47
  • Exactly, because my unit test DOM is not set up correctly. That is what I'm asking, how to set that up? – epatmalnieks Oct 04 '19 at 15:49
  • @epatmalnieks, I am confused, where is your testing code? I am expecting to see `it('shows something to the screen', () => {});` before the `const appStatus = document.querySelector('.appstatus');` – Daniel Feb 20 '20 at 04:20

0 Answers0