Home > OS >  How to conditionally skip a Mocha test in TypeScript
How to conditionally skip a Mocha test in TypeScript

Time:07-16

While this SO article covers how to skip tests in javascript. The discussion doesn't cover how to do the same thing in TypeScript.

Example of not working code:

describe('Example test suite',() => {  
                                                     
  before(async () => {                               
    if(true) {                                       
      console.log('Unexpected condition. Test results may be invalid. Skipping tests.');  
      this.skip();                                                                                      
    }                                                                                                      
  });                                                                                                      
                                                                                                           
  it('it will do something',async () => {                                                                  
    console.log('This should not run.');                                                                   
  });                                                                                                      
                           
});

Results:

error TS2532: Object is possibly 'undefined'.

CodePudding user response:

I used the CocNvim plugin for neovim to do some inline introspection into the mocha type definitions and found the following solution works:

describe('Example test suite',function(this:Mocha.Suite) {  
  const suite = this;                                  
                                                     
  before(async () => {                               
    if(true) {                                       
      console.log('Unexpected condition. Test results may be invalid. Skipping tests.');      
      suite.ctx.skip();                              
    }                                                
  });                                                
                                                     
  it('it will do something',async () => {            
    console.log('This will not run.');               
  });                                                  
});

Note the intentional use of function() instead of an arrow function in the describe handler. This is because arrow functions cannot define their this:type.

  • Related