Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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