node.jsasynchronoussubprocesstesting

我在node.js中做了第一步,想testing我的代码,但是我被卡住了。 我使用node-qunit库作为testing工具。

这是我的代码:

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; 

当我从交互式控制台调用这个函数时,它们按预期工作。 但是,当我尝试使用下面的代码asynchronoustesting它们时,第二个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); }); 

看起来问题是不同步的,因为当我单独testing这个函数时,它们都工作。

感谢您的帮助。

使用懒惰评估,而不是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'); }); });