custom_matcher.js |
|
---|---|
Often a project will want to encapsulate custom matching code for use across multiple specs. Here is how to create a Jasmine-compatible custom matcher. A custom matcher at its root is a comparison function that takes an |
|
This object has a custom matcher named "toBeGoofy". |
var customMatchers = {
|
Matcher FactoriesCustom matcher factories are passed two parameters: |
toBeGoofy: function(util, customEqualityTesters) {
|
The factory method should return an object with a |
return {
|
A Function to
|
compare: function(actual, expected) {
|
|
if (expected === undefined) {
expected = '';
}
|
ResultThe |
var result = {};
|
|
result.pass = util.equals(actual.hyuk, "gawrsh" + expected, customEqualityTesters);
|
Failure MessagesIf left |
if (result.pass) {
|
The matcher succeeded, so the custom failure message should be present in the case of a negative expectation - when the expectation is used with |
result.message = "Expected " + actual + " not to be quite so goofy";
} else {
|
The matcher failed, so the custom failure message should be present in the case of a positive expectation |
result.message = "Expected " + actual + " to be goofy, but it was not very goofy";
}
|
Return the result of the comparison. |
return result;
}
};
}
};
|
Custom negative comparatorsIf you need more control over the negative comparison (the |
|
Registration and Usage |
describe("Custom matcher: 'toBeGoofy'", function() {
|
Register the custom matchers with Jasmine. All properties on the object passed in will be available as custom matchers (e.g., in this case |
beforeEach(function() {
jasmine.addMatchers(customMatchers);
});
|
Once a custom matcher is registered with Jasmine, it is available on any expectation. |
it("is available on an expectation", function() {
expect({
hyuk: 'gawrsh'
}).toBeGoofy();
});
it("can take an 'expected' parameter", function() {
expect({
hyuk: 'gawrsh is fun'
}).toBeGoofy(' is fun');
});
it("can be negated", function() {
expect({
hyuk: 'this is fun'
}).not.toBeGoofy();
});
});
|