0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

jestを使って4つのフェーズでテスト

Last updated at Posted at 2020-10-14

テストにおける4つのフェーズについて

テストには、4つのフェーズでテストする方法があり、

1.準備(setup)、
2.実行(exercise)、
3.検証(verify)、
4.後片付け(teardown)
という流れになっています。

今回は、nodeで実装しています。

テストのときだけdynamoDBにデータを入れるようにし、
そのデータを使ってラムダを呼んだ時のテストをしています。

~意識すること~
➡test()の中でsetup~teardownを行う。そうすると、テストケースごとに、パラメータやテストデータやレスポンス内容などキレイに分けることができる。

1.準備(setup)
➡パラメータの用意をしたり、データベースにテスト用のデータを入れたり。
テスト前にあらかじめテスト用のデータを入れておくのもよいですが、
テストのときだけとあるデータを入れてテストをしたくなる場合があるので、
今回はテストのときにデータを入れる感じにしています。

2.実行(exercise)
➡テスト対象の関数を呼ぶ

3.検証(verify)、
➡jestのexpectを使ってレスポンス内容が意図したものになってるかを検証

4.後片付け(teardown)
➡DB接続を切断したりする例があったりしますが、そういうのは内部でやってるので今回は無し

プログラム

anime-suko.ts

const putHogeTable = () => {
  return new Promise((resolve) => {
    const items = [
      {
        id: 'hoge-00001',
        name: 'あやねる',
      },
      {
        id: 'hoge-00002',
        name: '小倉',
      },
    ]

    interface ItemsInterface {
      id: string
      name: string
    }

    const putRequest: { PutRequest: { Item: ItemsInterface } }[] = []
    items.forEach((item) => {
      const obj = {
        PutRequest: {
          Item: item,
        },
      }
      putRequest.push(obj)
    })

    const params = {
      RequestItems: {
        requester: putRequest,
      },
    }

    documentClient.batchWrite(params, (err, data) => {
      if (err) {
        console.log('[ERROR] ' + err)
        resolve(null)
      } else {
        resolve(data)
      }
    })
  })
}

//共通setup
const putCommon = () => {
  putHogeTable()
}

/*
 * 正常系1(全てのパラメータが存在する) 
 * 前提条件:パラメータ内にメッセージID(messageID)が存在すること
 * 期待結果:ステータスコードが200で返ってくること
 */
const testCase1 = test('正常系1(全てのパラメータが存在する)', async () => {
  //setup
  putCommon()
  const testSuccessParameterJson2 = {
    id: 'hoge-00001',
    messageID: 'hogeMessage1',
  }
  const testSuccessParameterStr2 = JSON.stringify(testSuccessParameterJson2)

  jest
    .spyOn(callLambdaModule, 'callLambda')
    .mockResolvedValueOnce(Promise.resolve({ statusCode: 200 }))
  const testSuccessExpectResponse = {
    statusCode: 200,
  }

  //Exercise
  const actual = await hogeLambdaFunction()

  //verify
  //ステータスコードが200で返ってくること
  expect(actual).toStrictEqual(testSuccessExpectResponse)
})

まとめ

jestでのテストの方法をググったりすると、普通にレスポンスが意図したものかどうかみたいな記事はいっぱい見つかるが、今回扱った4つのフェーズを
意識したテストというのを会社で学べたのは良かった。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?