LoginSignup
19
14

More than 5 years have passed since last update.

node.jsのCLIのテストをavaで書いてみる

Posted at

標準出力に'hello'の出力を期待する簡単なテストを書いてみます。
まずは、'hello'を出力するだけですが、cli.jsのプログラムです。

cli.js
#!/usr/bin/env node
'use strict';
console.log('hello');

実行権限を付加します。

$ chmod +x cli.js

avaを使って、CLI環境のテストをしてみます。avaとは並列実行可能なes6で書けるテストランナーです。内部でpower-assertが使われてるので、テストの結果がわかりやすいです。

sindresorhus/ava: Futuristic test runner

$ npm init
$ npm i -D ava pify

npm scriptsのtestにavaを指定します。

package.json
{
  "scripts": {
    "test": "ava"
  },
  "devDependencies": {
    "ava": "^0.13.0",
    "pify": "^2.3.0"
  }
}

テストを書いてみます。
execFileをpifyを使ってPromise化して、cli.jsの結果をawaitで受けます。avaではasync/awaitがデフォルトで使えるので使わない手はないでしょう。

test.js
import test from 'ava';
import pify from 'pify';
import {execFile} from 'child_process';

test('echo hello', async t => {
    const stdout = await pify(execFile)('./cli.js');
    t.is(stdout, 'hello\n');
});

実行

$ npm t

> @ test /Users/akameco/sandbox/stdout-test
> ava


   1 passed

通りました。

次に、新しいテストを追加して、1度テストを落としてみます。worldを引数にとって、hello worldと表示することを期待します。

test.js
import test from 'ava';
import pify from 'pify';
import {execFile} from 'child_process';

test('echo hello', async t => {
    const stdout = await pify(execFile)('./cli.js');
    t.is(stdout, 'hello\n');
});

test('echo hello world', async t => {
    const stdout = await pify(execFile)('./cli.js', ['world']);
    t.is(stdout, 'hello world\n');
});

テストを実行してみます。

$ npm t

> @ test /Users/akameco/sandbox/stdout-test
> ava


   1 passed
   1 failed

  1. args

  t.is(stdout, 'hello world\n')
       |
       "hello\n"

      _callee2$ (test.js:12:4)

npm ERR! Test failed.  See above for more details.

power-assertによって、今の状態がわかりやすく表示されます。
では、コマンドライン引数を受け取ってそれを表示するようにcli.jsを変更してみます。

cli.js
#!/usr/bin/env node
'use strict';
const args = process.argv.slice(2);
console.log('hello', ...args);

テストを実行します。

❯ npm t

> @ test /Users/akameco/sandbox/stdout-test
> ava


   2 passed

よさそうです。

まとめ

avaを使うことでシンプルにテストを書くことができるのがわかると思います。
日本語のドキュメントもあるので、参照してみるといいかもしれません。
ava-docs/readme.md at master · sindresorhus/ava-docs

参考

sindresorhus/ava: Futuristic test runner
power-assert-js/power-assert: Power Assert in JavaScript. Provides descriptive assertion messages through standard assert interface. No API is the best API.
ava-docs/readme.md at master · sindresorhus/ava-docs

19
14
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
19
14