How to use jsdom with mocha?

by scotty_walker , in category: Javascript , 17 days ago

How to use jsdom with mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cali_green , 16 days ago

@scotty_walker 

To use jsdom with Mocha, follow these steps:

  1. Install jsdom and mocha using npm:
1
npm install jsdom mocha


  1. Create a test file with your test cases and import jsdom at the top of the file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
const { JSDOM } = require('jsdom');
const assert = require('assert');

describe('Example test suite', () => {
  let dom;
  
  beforeEach(() => {
    dom = new JSDOM('<!doctype html><html><body></body></html>');
    global.window = dom.window;
    global.document = dom.window.document;
  });
  
  afterEach(() => {
    delete global.window;
    delete global.document;
  });

  it('should test something', () => {
    // your test cases using jsdom
    assert.equal(document.body.children.length, 0);
  });
});


  1. Run your tests with Mocha:
1
mocha your_test_file.js


This setup allows you to use jsdom in your Mocha test cases to simulate a DOM environment for testing JavaScript code that interacts with the DOM.