2014-12-18 8 views
12

Ho il seguente stile della funzione (usando promesse Bluebird sotto Node.JS):Test promessa catene con Mocha

module.exports = { 
    somefunc: Promise.method(function somefunc(v) { 
     if (v.data === undefined) 
      throw new Error("Expecting data"); 

     v.process_data = "xxx"; 

     return module.exports.someother1(v) 
      .then(module.exports.someother2) 
      .then(module.exports.someother3) 
      .then(module.exports.someother4) 
      .then(module.exports.someother5) 
      .then(module.exports.someother6); 
    }), 
}); 

che sto cercando di testare (utilizzando moka, Sinon, affermare) :

// our test subject 
something = require('../lib/something'); 

describe('lib: something', function() { 
    describe('somefunc', function() { 
     it("should return a Error when called without data", function(done) { 
      goterror = false; 
      otherexception = false; 
      something.somefunc({}) 
      .catch(function(expectedexception) { 
       try { 
        assert.equal(expectedexception.message, 'Expecting data'); 
       } catch (unexpectedexception) { 
        otherexception = unexpectedexception; 
       } 
       goterror = true; 
      }) 
      .finally(function(){ 
       if (otherexception) 
        throw otherexception; 

       assert(goterror); 
       done(); 
      }); 
     }); 
}); 

Tutto ciò funziona come tale, ma si sente contorto per uno.

Il mio problema principale è verificare la catena di promesse (e l'ordine) nella funzione. Ho provato diverse cose (fingere un oggetto con un metodo allora, che non ha funzionato, prendendolo in giro come un matto, ecc.); ma sembra che ci sia qualcosa che non vedo, e non sembra che stia ricevendo le documentazioni moca-o-sinon a questo riguardo.

Qualcuno ha qualche indicazione?

Grazie

conteggio

risposta

7

Mocha supporta promesse in modo che si possa fare questo

describe('lib: something', function() { 
    describe('somefunc', function() { 
     it("should return a Error when called without data", function() { 
      return something.somefunc({}) 
       .then(assert.fail) 
       .catch(function(e) { 
        assert.equal(e.message, "Expecting data"); 
       }); 
     }); 
    }); 
}); 

Questo è più o meno equivalente al codice sincrono:

try { 
    something.somefunc({}); 
    assert.fail(); 
} catch (e) { 
    assert.equal(e.message, "Expecting data"); 
} 
+0

come faccio beffe someother1- 6 in questo caso, quindi le implementazioni effettive non vengono chiamate? – berlincount

+0

hmm. Se l'asserzione nella cattura fallisce, sto ricevendo un "Possible nonhandled AssertionError", come posso fare in modo che bolla in modo corretto? – berlincount

+0

@berlincount stai usando una versione mocha che supporta le promesse? Se sì, sei sicuro di tornare alla catena delle promesse come nella risposta – Esailija