Skip to content

Instantly share code, notes, and snippets.

@dmarcelino
Created April 24, 2015 14:12
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 dmarcelino/e6b4a0b6d814e3fc906f to your computer and use it in GitHub Desktop.
Save dmarcelino/e6b4a0b6d814e3fc906f to your computer and use it in GitHub Desktop.
Optional Mocha tests: if not pass mark as pending
/**
* Sometimes there is the need to have optional tests that may need to run conditionally as discussed in:
* http://stackoverflow.com/questions/19075792/unit-tests-for-optional-units
* This solution is good but if our tests are part of a test suite that runs against many different kinds of implementations
* it may be desirable to have optional tests that "pass" if they are supported and become "pending" if they fail.
* This way we don't have to break the whole test suit because of an optional test breaksing and, if it passes, we'll know about it.
*/
function runOptionalTest(testName, failedMessage, testFn){
if(!testFn){
testFn = failedMessage;
failedMessage = 'WARN: ' + testName + ' is not supported';
}
testFn(function(result){
if(result){
it(failedMessage);
}
else {
it(testName, function(){});
}
});
}
describe('optional tests', function(){
var successTest = function(done){
done();
};
runOptionalTest('should do xyz', successTest);
var failedTest = function(done){
done(new Error('oops'));
};
runOptionalTest('should do xyz eventually', failedTest);
});
// Result:
// optional tests
// ✓ should do xyz
// - WARN: should do xyz eventually is not supported
@dmarcelino
Copy link
Author

I've consolidated this on https://github.com/dmarcelino/it-optional.

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