LoginSignup
2
2

More than 5 years have passed since last update.

Node.jsのAPIサーバーを起動してテストを実行するコマンドを作る お手製スクリプト編

Posted at

短い結論

  1. テスト単体とほとんど同じ表示が可能
  2. 実現コマンドを特定するのが面倒

背景

APIサーバーの起動とテストの実行が別のコマンドだとテストの実行が面倒です。

例えばsyamoと言うアプリケーションは、次のコマンドでサーバーを起動します。

npm start

別のターミナルでテストを実行します。

npm test

1コマンドにして、1ターミナルで実行したい思いがあります。

作戦

child_process.spawnを使う作戦です。
child_process.spawnはは、子プロセスを起動できます。

実行

準備

スクリプト

スクリプトを用意します。

test.js
const child_process = require('child_process'),
  server = child_process.spawn('node', ['node_modules/babel/lib/_babel-node', 'app.js']),
  test = child_process.exec('npm test', () => {
    server.kill()
    process.exit()
  })

test.stdout.pipe(process.stdout)

server.killは、起動した子プロセスは殺せます。しかし、孫プロセスが残ります。サーバーの起動コマンドとを直接指定する必要があります。
syamoはbabel-node(5.8.35)で起動しています。起動の仕方がちょっと変わっています。

起動コマンド

npm start後にps -efをすると、次のプロセスがわかります。

501  4408  4405   0  9:54AM ttys000    0:00.09 node /Users/shigerunakajima/syamo/node_modules/.bin/babel-node app.js
  501  4409  4408   0  9:54AM ttys000    0:00.98 /usr/local/bin/node /Users/shigerunakajima/syamo/node_modules/babel/lib/_babel-node app.js
/usr/local/bin/node /Users/shigerunakajima/syamo/node_modules/babel/lib/_babel-node app.js

のパスを修正して
node node_modules/babel/lib/_babel-node app.jsという起動コマンドがわかります。

実行

syamoは必要な環境変数が多いです。
node-foremanを使って、環境変数をファイルから読み込んでスクリプトを起動します。

node_modules/.bin/nf run node test.js

参考:node-foremanで環境変数をファイルから読み込んでコマンド実行

結果

サーバーのログとテスト結果が混ざって残念な感じです。

[OKAY] Loaded ENV .env File as KEY=VALUE Format

> syamo@0.0.2 test /Users/shigerunakajima/syamo
> mocha --require espower-babel/guess -c



  An authentication
    ✓ is errer by chatroom. (603ms)

  Issue
    ✓ is ok. (822ms)
    ✓ is ignored by duplicate.
    ✓ is not ignored that is sent to other chatroom. (692ms)
    ✓ is ignored by update action.
    ✓ is ignored by close action.

  MR
    ✓ is ok. (1341ms)
    ✓ is through that is unchecked. (780ms)
    ✓ is ignored thats status is merged.
    ✓ is error unless any information from Gitlab API. (293ms)

  Push
    ✓ is ok. (485ms)
    ✓ is ignored by total_commits_count 0

  A template
    ✓ is used for the chatroom. (413ms)


  13 passing (5s)

良い感じです。
mochaを単体で実行した場合と、ほぼ同じ出力が得られます。

補足

テストコードの出力に色をつけるには、mochaに-cオプションをつけます。

関連

Node.jsのAPIサーバーを起動してテストを実行するコマンドを作る node-foreman編

2
2
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
2