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 1 year has passed since last update.

jestでオブジェクトの配列の値が期待したものかをテストするパターン

Posted at

NestJSでAPIの開発をしています。
ふと、テストを書くことになりました。

基本的なコードですが、オブジェクトの配列に対してのテストコードの例があまり出てこなかったので、ここに残しておきます。

ポイントは、objectContainingarrayContainingです。

ともかく結論のコードから。

テストコード

describe('UserService', () => {
  const validObject = {
    data: [
      { id: 1, name: 'testUser1', description: 'description1' },
      { id: 2, name: 'testUser2', description: 'description2' },
      { id: 3, name: 'testUser3', description: 'description3' },
    ],
    total: 3,
  }

  const invalidObject = {
    data: [
      { id: '1', name: 'testUser1', description: 'description1' },
      { id: '2', name: 'testUser2', description: 'description2' },
      { id: '3', name: 'testUser3', description: 'description3' },
    ],
    total: 3,
  }

  // 説明用にモック関数を用意
  const mockValidFn = jest.fn(() => validObject)
  const mockInvalidFn = jest.fn(() => invalidObject)

  // OK
  it('should get users', async () => {
    // 期待されたレスポンス
    const result = mockValidFn()
    expect(result).toEqual(
      expect.objectContaining({
        total: expect.any(Number),
        data: expect.arrayContaining([
          expect.objectContaining({
            id: expect.any(Number),
            name: expect.any(String),
            description: expect.any(String),
          }),
        ]),
      })
    )
  })

  // NG
  it('should get users', async () => {
    // 誤ったレスポンス
    const result = mockInvalidFn()
    expect(result).toEqual(
      expect.objectContaining({
        total: expect.any(Number),
        data: expect.arrayContaining([
          expect.objectContaining({
            id: expect.any(Number),
            name: expect.any(String),
            description: expect.any(String),
          }),
        ]),
      })
    )
  })
})

※ 公式ドキュメントにも記載がありますが、あくまでobjectContainingオブジェクトに特定のキーがあるかどうかをチェックする関数なので、余分なキーがあった場合でも一致(OK)となります。

オブジェクトの配列を検証するもっといい方法があったら教えてください。

参考

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?