Skip to content

Instantly share code, notes, and snippets.

@kjlubick
Last active September 26, 2018 13:32
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 kjlubick/543e96f4774a286f3aabe72e7201e615 to your computer and use it in GitHub Desktop.
Save kjlubick/543e96f4774a286f3aabe72e7201e615 to your computer and use it in GitHub Desktop.
Custom matcher for Jasmine - matcher for a list of strings to have (at least) one that matches a given regex.
const toContainRegexMatcher = {
// see https://jasmine.github.io/tutorials/custom_matcher
// for docs on the factory that returns a matcher.
'toContainRegex': function(util, customEqualityTesters) {
return {
'compare': function(actual, regex) {
if (!(regex instanceof RegExp)) {
throw `toContainRegex expects a regex, got ${JSON.stringify(regex)}`;
}
let result = {};
if (!actual || !actual.length) {
result.pass = false;
result.message = `Expected ${actual} to be a non-empty array `+
`containing something matching ${regex}`;
return result;
}
for (let s of actual) {
if (s.match && s.match(regex)) {
result.pass = true;
// craft the message for the negated version (i.e. using .not)
result.message = `Expected ${actual} not to have anyting `+
`matching ${regex}, but ${s} did`;
return result;
}
}
result.message = `Expected ${actual} to have something matching ${regex}`;
result.pass = false;
return result;
},
};
},
};
describe('my thing', function() {
beforeEach(function() {
jasmine.addMatchers(toContainRegexMatcher);
});
it('does some sort of test', function() {
expect(['alpha', 'beta', 'gamma']).toContainRegex(/.*et.*/);
expect(['alpha', 'beta', 'gamma']).not.toContainRegex(/golf.*/);
});
});
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment