2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Node] 標準入力を扱うコードをテストする

Posted at

ユーザからの入力を受け付けるCUIのようなコードのテストサンプル。

テスト対象コード

prompt.js
const readline = require('readline');

const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

module.exports = function prompt(question) {
  return new Promise((resolve, reject) => {
    rl.question(question, answer => {
      rl.close();
      resolve(answer);
    });
  })
};

使う側はこんな感じ。

main.js
const prompt = require('./prompt');

prompt('Enter something: ').then(answer => {
  console.log(answer);
});

実行結果

% node ./main.js
Enter something: abc
abc

テストコード

spec/prompt-spec.js
const prompt = require('../prompt');

describe('prompt function', () => {
  it('returns answer', done => {
    prompt('question: ').then(answer => {
      expect(answer).toEqual('abc');
      done();
    });
    process.stdin.emit('data', 'abc\n');
  });
});
2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?