2012-05-14 7 views
11

Sto cercando di stub seguente:Come faccio a stub un emettitore evento con Sinon.js

on('complete', function(data){ }); 

voglio solo chiamare la callback se il primo parametro è 'completo'.

La funzione sto testando contiene anche:

on('error', function(data){ }); 

quindi non posso fare appena cedere causa che il fuoco sia il completo e la richiamata errore.

Se non volessi usare sinon, lo farei scrivendo quanto segue.

var on = function(event, callback){ 
    if (event === 'complete'){ 
    callback('foobar'); 
    }; 
}; 
+0

Can voi mostra un esempio più completo della funzione che contiene questo? –

risposta

0

forse è possibile utilizzare un spyCall:

var spy = sinon.spy(window, 'on'); 
on('error', function(data){ }); 
on('complete', function(data){ }); 
for(var i=0; i < spy.callCount; i++){ 
    var call = spy.getCall(i); 
    if(call.args[0] === 'complete') call.args[1]('foobar'); 
} 
7

È possibile restringere le circostanze in cui un yield avviene per la combinazione con un withArgs in questo modo ...

on.withArgs('complete').yields(valueToPassToCompleteCallback); 
on.withArgs('error').yields(valueToPassToErrorCallback);