Skip to content

Instantly share code, notes, and snippets.

@trotzig
Created January 25, 2015 02:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trotzig/24d7e9119b355fb44785 to your computer and use it in GitHub Desktop.
Save trotzig/24d7e9119b355fb44785 to your computer and use it in GitHub Desktop.
A custom Jasmine matcher to check a component for a particular string
var $ = require('jquery');
var resolveDOMNode = require('support/resolve_dom_node');
/**
* This file adds a `toHaveText` matcher to our Jasmine spec. To use it, do
* something like:
*
* expect(component).toHaveText('Support John');
*/
beforeEach(function() {
jasmine.addMatchers({
toHaveText: function() {
return {
/**
* @param {Object} node A rendered React component, or a DOM node
* @param {string} expectedText The text you expect this node/component
* to have
* @param {Object} options
* @param {boolean} options.exact if true, performs an exact match
* @param {boolean} options.caseInsensitive if true, performs a
* case-insensite match.
* @return {Object}
*/
compare: function(node, expectedText, options = {}) {
var result = {},
domNode = resolveDOMNode(node),
actualText = $(domNode).text(),
contain = 'contain';
if (options.caseInsensitive) {
actualText = actualText.toLowerCase();
expectedText = expectedText.toLowerCase();
}
if (options.exact) {
result.pass = actualText === expectedText;
contain = 'be';
} else {
result.pass = actualText.indexOf(expectedText) !== -1;
}
if (result.pass) {
result.message = `Expected "${actualText}" not to ${contain} "${expectedText}"`;
} else {
result.message = `Expected "${actualText}" to ${contain} "${expectedText}"`;
}
return result;
}
};
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment