vendredi 8 juillet 2016

Sinon callback doesn't trigger stub/spy

I want to test a program that I'm writing with mocha, chai and sinon. The basic idea behind the program is that it opens a serialport and defines a few functions that get triggered by its callback, i.e. something like this:

function sPort () {
   this.serialport = undefined;
   this.isConnected = false;
   this.port = undefined;

   this.connect(port, errorCallback) {
      if (this.isConnected) {
            if (errorCallback !== undefined)
                errorCallback('already connected');
            }
            return;
      }
      this.port = port;
      this.serialport = new SerialPort(this.port, {
            autoOpen: false,
            baudrate: 9600,
            dataBits: 8,
            stopBits: 1,
            parity: 'none'
        });
      this.serialport.on('open', this.handleConnect.bind(this));
      this.serialport.on('data', this.handleIncomingData.bind(this));
      this.serialport.on('error', this.handleConnectionError.bind(this));
      this.serialport.on('close', this.handleConnectionClose.bind(this)); 
      this.serialport.on('disconnect', this.handleDisconnect.bind(this));
      this.serialport.open(); 
   }
   this.disconnect() {
      this.serialport.close()
   }
   this.handleConnectionClose(){
      this.isConnected = false;
      this.serialport = undefined;
   }
}

Now I want to test this with sinon, and check if the, e.g. this.handleConnectionClose() is being called when I close the serialport. I first tried to do this with

describe('sPort', function(){
    it('should close the connection', function() {
        var conClose = sinon.spy(sPort, 'handleConnectionClosed')
        sPort.disconnect();
        sinon.assert.called(conClose)
        assert.isFalse(sPort.isConnected);
        expect(sPort.serialport).to.equal(undefined)
    }
}

but all 3 assertions failed. I figured that would be caused by the asynchronicity of serialport.close() and this test would be performed before the event was actually triggered. Then I changed the spy into a stub, which did pretty much the same as the original function, but that had the same effect. I think that might have the same reason as before, but I don't know what I can do to get the results I'm hoping for.

Aucun commentaire:

Enregistrer un commentaire