LoginSignup
5
4

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-09-29

やりたい事

JavaScript の単体テストで、テスト対象のコードがサーバと通信して JSON 形式で受信を受け取る場合、サーバと通信する部分を置き換えてテストコード内部で完結するようにしたい。
しかし、通信する部分をモックで置き換えるのはしたくないので、テスト用に JSON を返すサーバを立てたい、そしてサーバは開始時に起動、終了時に停止させたい。

どうやるか

json-serverこんな感じに サーバの実装をすればできる。
json-server は、パスと返る JSON の内容をコードから指定できるので、テストケースに合わせてテストコード内で修正できる。

実装例

var jsonServer = require("json-server");
var assert = require("assert");
var http = require("http");

describe("json test", () => {
    let server;
    before(() => {
        const app = jsonServer.create();
        const router = jsonServer.router(
            {"tasks": [{"description": "first context"},{"description":"second text"}]});
        const middleware = jsonServer.defaults();

        app.use(middleware);
        app.use(router);
        server = app.listen(8080, () => {
            console.log("started");
        });
    });
    after(() => {
        server.close(() => {
            console.log("closed");
        });
    });

    it("test 1", (done) => {
       http.get("http://localhost:8080/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();
          });
       }); 
    });
});

実行例

% ./node_modules/.bin/mocha


  json test
started
GET /tasks 200 9.264 ms - 88
    ✓ test 1 (38ms)

closed

  1 passing (67ms)
5
4
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
5
4