LoginSignup
0
0

More than 5 years have passed since last update.

単体テストで開始時にモックサーバを起動し、終了時に停止する: その 2

Last updated at Posted at 2018-10-01

やりたい事

前回の、単体テストで開始時にモックサーバを起動し、終了時に停止する - Qiita では json-server をライブラリとして使ってサーバを起動・終了する手順を書きました。
json-server はコマンドラインからの実行もできるので、そちらを利用した書き方です。

前回の記事は、mocha 単体では実行できたのですが mocha-webpack を使った時に、うまく動かなかったので、そういう場合の回避策として調べました。

どうやるか

child_process.spawn を使ってコマンドを (background で) 起動し、標準出力への出力内容から起動したかどうかを確認します。
終了は、起動時の PID を記録しておき、それを kill することで実現します。

実装例

import * as child_process from "child_process";
import assert from "power-assert";
import http from "http";

describe('load with stub', function() {
    this.timeout(100000);
    let child;
    before(() => {
        return new Promise((resolve) => {
            child = child_process.spawn(
                "/home/example/server_test/node_modules/.bin/json-server",
                ["test_sample.json"],
                {detached: true, stdio: ['ignore', 'pipe', 'ignore']});
            child.stdout.on('data', (data) => {
                //console.log("before(): " + data.toString());
                if (data.toString().indexOf("Type s + enter at any time to create a snapshot of the database") >= 0) {
                    resolve();
                }
            });
        });
    });
    after(() => {
        // 起動した json-server を kill
        child_process.execFile("/bin/kill", [child.pid]);
    });

    it("test 1", (done) => {
       http.get("http://localhost:3000/tasks", (res) => {
          let body = '';
          res.setEncoding('utf-8');
          res.on('data', (chunk) => {
              body += chunk;
          });
          res.on('end', (res) => {
              res = JSON.parse(body);
              assert(res[0].description == 'first context');
              assert(res[1].description == 'second text');
              done();
          });
       }); 
    });
});

json-server はコマンドラインから起動すると、最後に "Type s + enter at any time to create a snapshot of the database" という文字列を出すのでそれが出ているかどうかで判定しています。
kill の方が execFile になっているのは深い理由はありません、こちらも spawn 使っても実装できます。

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