使用读取流对功能进行单元测试

时间:2020-04-08 14:58:17

标签: javascript stream mocha sinon tail

我正在尝试使用读取流测试以下功能。

module.exports = async (taskDir, taskLogger) => { // add parameter for startPosition?
  if (!fs.existsSync(join(taskDir, 'out.log'))) throw new Error('File Doesn\'t Exists');

  const fileStream = createReadStream(join(taskDir, 'out.log'), {
    encoding: 'utf8',
    start: startPosition,
    tail: true,
  });

  debug('File Stream Created');

  const rl = readline.createInterface({
    input: fileStream,
    crlfDelay: Infinity,
  });

  debug('Line Interface Created');

  // Follow the file
  rl.on('line', (line) => {
    outInfo = { currentPosition: fileStream._getBytesRead() };
    debug('Writing Line to File');
    fs.writeFile(join(taskDir, 'outInfo.json'), JSON.stringify(outInfo), () => {});
    debug('Written Line to File');
    taskLogger.log(line);
  });
};

我的测试集中在taskLogger.log()被调用的周围。理想情况下,它假定遵循以下过程,将输出重定向到文件。我试图避免在测试中使用spawn并手动将其写入文件。

tail模块到达创建线接口的地步,但是line事件似乎永远不会触发,即使我在稍等片刻之后再次写入文件。在函数上下文中,asyncSleep()setTimeout()const asyncSleep = promisify(setTimeout);

的包装
describe.only('Testing TAIL Module', () => {
  it('Should Output Data to the Console', async () => {
    // Setup
    fs.removeSync('/tmp/runner-test-task/out.log');
    debug('/tmp/runner-test-task/out.log, REMOVED');
    fs.writeFileSync('/tmp/runner-test-task/out.log', '1');

    if (!fs.existsSync('/tmp/runner-test-task/out.log')) throw new Error('File Doesn\'t Exists');
    debug('/tmp/runner-test-task/out.log CREATED');

    // Test
    const logSpy = sinon.spy(console, 'log');
    tail('/tmp/runner-test-task', logSpy);
    await asyncSleep(500);

    expect(logSpy).to.have.been.called;
    logSpy.resetHistory();

    fs.writeFileSync('/tmp/runner-test-task/out.log', '2');
    await asyncSleep(500);
    expect(logSpy).to.have.been.called;
  });
});

任何可能的原因?最好的测试方法是什么?

0 个答案:

没有答案