Last active
          August 25, 2023 13:59 
        
      - 
      
 - 
        
Save haroldtreen/5f1055eee5fcf01da3e0e15b8ec86bf6 to your computer and use it in GitHub Desktop.  
    Testing promise rejection with Mocha
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | const { assert } = require('chai'); | |
| function isError(e) { | |
| if (typeof e === 'string') { | |
| return Promise.reject(new Error(e)); | |
| } | |
| return Promise.resolve(e); | |
| } | |
| describe('Promise Testing', () => { | |
| // With done callback - 8 lines | |
| it('should test rejections using done', (done) => { | |
| aMethodThatRejects() | |
| .then(() => { | |
| done(new Error('Expected method to reject.')) | |
| }) | |
| .catch((err) => { | |
| assert.isDefined(err); | |
| done(); | |
| }) | |
| .catch(done); | |
| }); | |
| // With built in Promise support - 8 lines + helper | |
| it('should test rejections using catch', () => { | |
| return aMethodThatRejects() | |
| .then(() => { | |
| return Promise.reject('Expected method to reject.'); | |
| }) | |
| .catch(isError) | |
| .then((err) => { | |
| assert.isDefined(err); | |
| }); | |
| }); | |
| }); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment
  
            
Using node's
assertmodule I was able to do this: