31
15

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 の toBe と toEqual の違いを比較

Posted at

1時間ほどハマったのでメモを。

toBe と toEqual の使い所

  • number, string の比較ならどちらでも良さそう。
  • object を比較する場合は、 toEqual 。

number, string

どちらも期待通りの結果に。

    it('number', () => {
      expect(1 + 1).toBe(2) // ok
      expect(1 + 1).toEqual(2) // ok
    })
    it('string', () => {
      expect('d' + 'b').toBe('db') // ok
      expect('d' + 'b').toEqual('db') // ok
    })

object

同じデータが入っていても toBe だと Fail します。

    it('object', () => {
      const user = { name: 'Hoge', age: 30 }
      // expect(user).toBe({ name: 'Hoge', age: 30 }) // Fail
      expect(user).toEqual({ name: 'Hoge', age: 30 })
    })

もともと日付の比較でハマってました。 Date は toEqual を利用しましょう。

    it('date', () => {
      const date = new Date('2020/01/01 00:00:00')
      // expect(date).toBe(new Date('2020/01/01 00:00:00')) // Fail
      expect(date).toEqual(new Date('2020/01/01 00:00:00'))
    })

new したインスタンスの比較も同様です。

    it('class', () => {
      class User {
        age: number
        constructor(age:number) {
          this.age = age
        }
      }
      const user = new User(30)
      // expect(user).toBe(new User(30)) // Fail
      expect(user).toEqual(new User(30))
    })

object の id が異なるからでしょうか。

参考

31
15
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
31
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?