LoginSignup
2
0

More than 5 years have passed since last update.

[メモ]fastifyのhttp injection機能

Last updated at Posted at 2018-02-25

http injection

  • fastifyのinstanceを作成する。
app.js
const app = require('fastify')();

app.get('/users/:id', (req, reply) => {
  reply.send({ id: 2, name: 'piyo' });
});

app.post('/users', (req, reply) => {
  reply
    .code(201)
    .send({ id: 3, name: 'hogehoge' });
});

module.exports = app;
  • http injection機能を利用する際は、injectメソッドを使用する。

  • サーバをlistenすることなく、テスト等を実行できる。

test.js
const test = require('tape');
const app = require('./app');

test.onFinish(() => {
  app.close();
});

test('GET /users/:id', async t => {
  t.plan(3);

  try {
    // 第2引数にNodeスタイルのcallback関数を渡すこともできる。
    // 省略した場合は、Promiseが返却される。
    const res = await app.inject({
      method: 'GET',
      url: '/users/2'
    });

    // tests
    t.equal(res.statusCode, 200);
    t.equal(res.headers['content-type'], 'application/json');
    t.deepEqual(JSON.parse(res.payload), {
      id: 2, 
      name: 'piyo'
    });
  } catch (e) {
    t.fail(e.message);
  }
});

  • リクエストボディを指定したい場合は、payloadプロパティに値を設定する。
test('POST /users', async t => {
  t.plan(4);

  try {
    const res = await app.inject({
      method: 'POST',
      url: '/users',
      payload: { name: 'hogehoge' }
    });
    const payload = JSON.parse(res.payload);

    t.equal(res.statusCode, 201);
    t.equal(res.headers['content-type'], 'application/json');  
    t.equal(payload.name, 'hogehoge');
    t.ok(payload.hasOwnProperty('id'));
  } catch (e) {
    t.fail(e.message);
  }
});
2
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
2
0