chai-jq - jQuery Assertions for Chai
A New jQuery Plugin for Chai
Chai is a wonderful JavaScript test assertion library that I rely on extensively (usually using it in conjunction with the Mocha test framework library). Chai has an intuitive, natural-language approach to assertions that enables you tests to read almost like an English narrative. Chai also supports plugins which extend the base assertion API.
Chai is quite often used for frontend JavaScript testing, and specifically for
testing jQuery elements in an application web page. There is an existing
chai-jquery plugin for Chai, which is extensive and really
quite neat. Unfortunately, it has a few issues with
overriding built-in Chai assertions like have
and length
in ways that
changes the underlying Chai API.
With that motivation in mind, I hacked together a quick jQuery plugin,
chai-jq
for Chai that has a separate $
-prefixed namespace to
avoid collisions with existing Chai assertions, and put the project up on
GitHub.
The chai-jq Plugin
The chai-jq
plugin has full documentation at the
project website, including installation instructions.
The plugin works in all of the following environments:
- Browser: Via a standard
<script>
tag include. - Browser + AMD: Via an AMD library like RequireJS.
- Node.js + JsDom: In Node.js using the JsDom browser environment emulator.
In terms of what chai-jq
provides, here is a brief tour of the
API (stolen from the project docs):
.$visible
Asserts that the element is visible.
See: http://api.jquery.com/visible-selector/
.$hidden
Asserts that the element is hidden.
See: http://api.jquery.com/hidden-selector/
.$val(string|regexp)
Asserts that the element value matches a string or regular expression.
See: http://api.jquery.com/val/
.$class(string)
Asserts that the element has a class match.
See: http://api.jquery.com/hasClass/
.$attr(name, string)
Asserts that the target has exactly the given named attribute, or
asserts the target contains a subset of the attribute when using the
include
or contain
modifiers.
See: http://api.jquery.com/attr/
.$prop(name, value)
Asserts that the target has exactly the given named property.
See: http://api.jquery.com/prop/
.$html(string)
Asserts that the target has exactly the given HTML, or
asserts the target contains a subset of the HTML when using the
include
or contain
modifiers.
See: http://api.jquery.com/html/
.$text(string)
Asserts that the target has exactly the given text, or
asserts the target contains a subset of the text when using the
include
or contain
modifiers.
See: http://api.jquery.com/text/
.$css(name, string)
Asserts that the target has exactly the given CSS property, or
asserts the target contains a subset of the CSS when using the
include
or contain
modifiers.
See: http://api.jquery.com/css/
The chai-jq
plugin is just getting off the ground and is
likely still rough around the edges. Any issue reports,
pull requests, and feedback are most welcome.