Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mock dom elements when using mocha javascript?

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?

like image 684
Shaked Avatar asked Jul 04 '17 13:07

Shaked


1 Answers

JSDOM is convenient because it allows you to test against a "real" DOM implementation without the overhead of running in a web browser.

If you can run your unit tests inside a browser you can assert against the DOM in the same way:

describe("the super special button", () => {

  it("adds an image", (done) => {
    const button = document.querySelector(".js-super-special");
    button.click();

    // give the browser a chance to update the DOM
    setTimeout(() => {
      const image = document.querySelector(".js-image")

      // using assertion library, like chai
      expect(image).to.not.beNull();

      // or using a port of Node's `assert` from a bundler like browserify:
      assert(image != null);

      done();
    })
  })
});
like image 129
joews Avatar answered Nov 08 '22 19:11

joews