简体   繁体   中英

Emit function on sinon mock

I have a function that I need to test using sinon. It takes two arguments and has different events that can be raised. I'm trying to simulate the 'ready' evet made to simulate a successful SFTP connection

function configureSFTPConnection(conn, connectionSettings) {
    'use strict';

    return new Promise(function(resolve, reject) {
        conn.on('ready', function() {
            resolve(conn);
        }).on('error', function(err) {
            reject(err);
        }).connect(connectionSettings);
    });
}

I can simulate the exterior connect function.

configureSftpStub = sinon.stub(clientObject, 'connect');

How can I force the ready callback to execute, completing the promise?

This is what I'm trying:

clientObject = new client();           
configureSftpStub = sinon.stub(clientObject, 'connect');
configureSftpStub.onCall(0).returns(function() {
    console.log('trying to do something');
    resolve();
});

The .onCall() never seems to run.

What was needed was rather than trying to return something I needed to replace the function that was called and do a simple .emit call within the function.

configureSftpStub = sinon.stub(clientObject, 'connect', function() {
    this.emit('ready');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM