2012-07-16 77 views
2

我做我的第一個步驟中的Node.js和想測試我的代碼,但我堅持。我用node-qunit庫作爲測試工具。Node.js的異步子進程測試

這裏是我的代碼:

var spawn = require('child_process').spawn; 
var ok = require('assert').ok; 

function _call_gpg(stdin_pass, passphrase, decrypt, callback) { 
    ok(stdin_pass); 
    ok(passphrase); 

    var buffers = []; 
    var gpg = spawn('gpg', ['--passphrase', passphrase, decrypt ? '-d' : '-c', '--no-use-agent']); 

    gpg.stdout.on('data', function(data) { 
     buffers.push(data); 
    }); 

    gpg.on('exit', function(return_code) { 
     callback(return_code === 0 ? Buffer.concat(buffers) : undefined); 
    }); 

    gpg.stdin.write(stdin_pass); 
    gpg.stdin.end(); 
} 

function encrypt(string, passphrase, callback) { 
    ok(typeof callback === 'function'); 

    _call_gpg(string, passphrase, false, function(buf) { 
     callback(buf && buf.toString('base64')); 
    }); 
} 

function decrypt(encoded_string, passphrase, callback) { 
    ok(typeof callback === 'function'); 

    raw_encoded_string = new Buffer(encoded_string, 'base64'); 
    _call_gpg(raw_encoded_string, passphrase, true, function(buf) { 
     callback(buf && buf.toString('utf8')); 
    }); 
} 

exports.encrypt = encrypt; 
exports.decrypt = decrypt; 

當我打電話從交互式控制檯這個功能,他們正常工作。但是,當我嘗試異步測試他們使用下面的代碼,第二strictEqual有時工作,有時失敗。

asyncTest('encrypting and decrypting', function() { 

    encrypt('foo', 'pass', function(encoded_string) { 
     decrypt(encoded_string, 'pass', function(decoded_string) { 
      strictEqual('foo', decoded_string, 'encryption and decryption work'); 
     }); 
    }); 

    decrypt('jA0EAwMCNiwPDFiMxvFgyRmB4axFyanuy2DZmB0ZIUfpXcASCKT8pwFm', 'pass', function(decoded_string) { 
     strictEqual('foo', decoded_string, 'only decryption works'); 
    }); 

    setTimeout(function() { start(); }, 10000); 
}); 

貌似問題與異步的,因爲當我分別測試這個功能,他們兩人的工作。

感謝您的幫助。

回答

0

使用懶評價,而不是setTimeout

asyncTest('encrypting and decrypting', function() { 

encrypt('foo', 'pass', function(encoded_string) 
    { 
    decrypt(encoded_string, 'pass', function(decoded_string) 
    { 
    /* Call start() as part of the output */ 
    strictEqual('foo', decoded_string, 'encryption and decryption work' && start()); 
    }); 
    }); 

decrypt('jA0EAwMCNiwPDFiMxvFgyRmB4axFyanuy2DZmB0ZIUfpXcASCKT8pwFm', 'pass', function(decoded_string) 
    { 
    /* Do not call start() */ 
    strictEqual('foo', decoded_string, 'only decryption works'); 
    }); 

});