How do I mock dom elements when using mocha javascript?

Viewed 6237

I'm using mocha to test my JavaScript code. The code involves html and css and implements a chat app. As far as I saw, Mocha can test JavaScript functions by matching the expected value to the function's return value.

But what if I want to test functions that don't return a value? Functions that mainly deal with DOM elements. (Like appending an image for example ).

How exactly can I mock DOM elements in mocha and then test if the function succeeds in generating the appropriate DOM elements?

I had looked around and found it was possible with selenium webdriver and jsdom. Is it possible to do this test with mocha alone and no other additional interfaces?

3 Answers

you can use jsdom-global package alternative that also works outside of Mocha. mocha-jsdom still works, but jsdom-global is better supported.

npm install --save-dev --save-exact jsdom jsdom-global

modify npm test script to be:

"test": "mocha -r jsdom-global/register"

test example: app.test.js

import {JSDOM} from 'jsdom'; // can also use common js

describe('DOM', () => {
  it('should log selector list', () => {
    const dom = new JSDOM(
      `<html>
         <body>
           <div class="card">1</div>
           <div class="card">2</div>
           <div class="card">3</div>
         </body>
       </html>`,
     {url: 'http://localhost'},
    );
  });

  global.document = dom.window.document;
  console.log(document.querySelectorAll('.card'));
});


Related