Adam
Adam

Reputation: 4074

Testing elements with jQuery-Chai

I have a couple of functions that use jQuery. And I'm having trouble making sense of the proper way to test them with jQuery-Chai in Mocha+Chai.

I see the list of assertions in the jQuery-Chai plugin. However, I don't understand where we get the DOM data to run those assertions?

Ideally I want to insert a line of html. Run the function on it. And use the jQuery-Chai assertion to validate.

Can someone help clear up where I would include the fixture to test these functions?

Thanks in advance.

Using: Testem with Mocha+Chai.

Upvotes: 3

Views: 1275

Answers (1)

Nathan Thompson
Nathan Thompson

Reputation: 2384

As you noted, chai-jquery only provides the assertions you can use against DOM elements. You'll need to use a different library to actually populate the DOM. Since you already need jQuery included for chai-jquery to work, the simplest solution may be to use jQuery's append() function to add child elements to the DOM, then remove them at the end of the test using jQuery's remove() function.

Alternatively, if you want to abstract away the DOM manipulation a bit, you could try pulling in a fixtures library. My favorite for this purpose is js-fixtures. You can still easily insert a single line of html using the set() function if that's all you need:

fixtures.set('<div>Your html here</div>');

If your test html becomes more complex though, you can extract it out into a sample html file and load the entirety of it into the DOM with the load() function:

fixtures.load('yourTestPage.html');

Finally, when your test is finished, you can easily clean your fixture using fixtures.cleanUp().

Upvotes: 1

Related Questions