mocha.js - How to programmatically skip a test in mocha?

ID : 20364

viewed : 8

Tags : mocha.jsmocha.js

Top 5 Answer for mocha.js - How to programmatically skip a test in mocha?

vote vote

97

You can skip tests by placing an x in front of the describe or it block, or placing a .skip after it.

xit('should work', function (done) {});  describe.skip('features', function() {}); 

You can also run a single test by placing a .only on the test. for instance

describe('feature 1', function() {}); describe.only('feature 2', function() {}); describe('feature 3', function() {}); 

Only the feature 2 block would run in this case.

There doesn't appear to be a way to programmatically skip tests, but you could just do some sort of check in a beforeEach statement and only run the test if the flag was set.

beforeEach(function(){     if (wrongEnvironment){         runTest = false     } }  describe('feature', function(){     if(runTest){          it('should work', function(){             // Test would not run or show up if runTest was false,          }     } } 
vote vote

89

Use Mocha's skip() function

It can be used to either statically to disable a test or entire suite, or dynamically skip it at runtime.

Here's an example runtime usage:

it('should only test in the correct environment', function() {   if (/* check test environment */) {     // make assertions   } else {     this.skip();   } }); 
vote vote

74

This answer does work for ES6.

Instead of:

describe('your describe block', () => { 

You want:

(condition ? describe : describe.skip)('your describe block', () => { 

This conditionally skips all tests in the describe block IF the condition is false.

Or, instead of:

it('your it block', () => { 

You want:

(condition ? it : it.skip)('your it block', () => { 

This conditionally skips one test IF the condition is false.

vote vote

64

I use runtime skipping from Mocha for the same scenario as you're describing. It is the copy paste from the docs:

it('should only test in the correct environment', function() {   if (/* check test environment */) return this.skip();    // make assertions }); 

As you can see, it skips the test based on environment. My own condition is if(process.env.NODE_ENV === 'continuous-integration').

vote vote

54

to skip tests, use describe.skip or it.skip

describe('Array', function() {   it.skip('#indexOf', function() {     // ...   }); }); 

to include tests you could use describe.only or it.only

 describe('Array', function() {   it.only('#indexOf', function() {     // ...   }); }); 

More info at https://mochajs.org/#inclusive-tests

Top 3 video Explaining mocha.js - How to programmatically skip a test in mocha?

Related QUESTION?