LoginSignup
0
0

More than 3 years have passed since last update.

AzureFunctionsのTypeScript関数のテストでcontextオブジェクトをモックしたい

Last updated at Posted at 2020-12-20

はじめに

株式会社センシンロボティクスの @s-okamura です。社内では主にフロントエンド/バックエンド実装およびインフラ構築を担当しています。今回はAzureFunctionsのTypeScript関数のユニットテストを作成する場合に、contextをモックする方法を紹介します。

概要

AzureFunctionsのトリガー関数は第1引数として context オブジェクトが渡され、バインディングデータの受け渡しやログ出力、レスポンスなどに使用されます。jestのユニットテストを作成する際、この context オブジェクトをモックしたいケースがあり、その方法を調査しました。

関数例

何か処理をして正常終了するような、非常にシンプルなQueueトリガーな関数の例です。

import {AzureFunction, Context} from '@azure/functions';

const queueTrigger: AzureFunction = async function (context: Context, queueMessage: string): Promise<void> {
  // do something 
  context.res = {
    status: 200
  }
};

export default queueTrigger;

方法

こちらの jest-mock-extended を利用します。ドキュメントに従いインストールすると、const context = mock<Context>() とすることでcontextオブジェクトをモックすることができます。

import {mock} from 'jest-mock-extended';
import {Context} from '@azure/functions';
import queueTrigger from 'index';

test('context.res.statusが200であること', async () => {
  // Contextオブジェクトをモックする
  const context = mock<Context>();
  await queueTrigger(context, 'test-message');
  expect(context.res.status).toEqual(200);
});
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