Skip to content

Instantly share code, notes, and snippets.

@scottrippey
Last active August 29, 2015 14:16
Show Gist options
  • Save scottrippey/a217c6b7596ad070dfaf to your computer and use it in GitHub Desktop.
Save scottrippey/a217c6b7596ad070dfaf to your computer and use it in GitHub Desktop.
Jasmine test cases - "these"
describe("typeof", function() {
these("expects ", {
"0 to output number": [ 0, "number" ],
"NaN to output number": [ NaN, "number" ],
"undefined to output undefined": [ undefined, "undefined" ],
"null to output object": [ null, "object" ],
"Date to output object": [ new Date(), "object" ],
"{} to output object": [ {}, "object" ],
"anon function to output object": [ function(){}, "object" ],
}, function(input, expectedOutput) {
var actualOutput = typeof input;
expect(actualOutput).toBe(expectedOutput);
});
});
// Note: credit goes to William Cowell for creating this extremely helpful test-case runner!
/**
* Creates a bunch of "it" blocks, one for each test case.
*
* @param {String} desc - Describes all test cases
* @param {Object.<string, Array>} testCases
* @param {String} testCases.<key> - Describes each test case
* @param {Array} testCases.<value> - An array of args that will be passed to the test
* @param {Function(...)} test - This test will be called once for each test case
*/
function these(desc, testCases, test) {
_these(it, desc, testCases, test);
}
function xthese(desc, testCases, test) {
_these(xit, desc, testCases, test);
}
function _these(it, desc, testCases, test) {
Object.keys(testCases).forEach(function (testCaseName) {
var testCaseArguments = testCases[testCaseName];
it(desc + testCaseName, function () {
test.apply(null, testCaseArguments);
});
});
}
@scottrippey
Copy link
Author

In this example, these will generate 7 it blocks, such as
it("expects 0 to output number", ...) and
it("expects NaN to output number", ...).

Each test case will call the test function with the supplied arguments.
Nice, simple, and extraordinarily helpful!!!

@scottrippey
Copy link
Author

Side note: semantically, these is not a good term, because you're not supposed to be describing the test cases.
However, I cannot think of a better term, apart from creating an overload for it.
Ideally, if merged into jasmine, an overload of it would be achievable. But as a "stand alone" utility, these will have to be good enough.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment