Jest.js 为什么下面的expect. toThrowError没有在我的终端中记录任何东西?

mrzz3bfm  于 8个月前  发布在  Jest
关注(0)|答案(2)|浏览(81)

我有一个助手,只是抛出一个错误:

export const checkPanoramaFormat = (panorama) => {
  if (!panorama.objectId) {
    throw new Error('panorama id is required')
  }
}

字符串
这是我的测试:

import {
  checkPanoramaFormat
} from '@/common/helpers'

describe('checkPanoramaFormat', () => {
  const panorama = { anotherProp: '1' }

  it('creates clone', () => {
    expect(checkPanoramaFormat(panorama)).toThrowError('hshshs')
  })
})


我期望终端显示我期望的和我得到的。但是我什么也没有得到。事实上,Jest什么也没有告诉我:


的数据
为什么会这样以及如何修复它?

7kjnsjlb

7kjnsjlb1#

试试看:

expect(() => {
  checkPanoramaFormat(panorama)
}).toThrow('hshshs')

字符串
如果你立即调用函数作为expect参数,它将在Assert之前抛出异常。它不在try/catch块内。你应该传递一个函数处理程序给expect,只在Assert时调用。我把它放在一个箭头函数中,但它可以被称为其他形式,例如:

expect(myFunc) // no arguments
expect(myFunc.bind(this, arg1, arg2)) // using .bind to set arguments for later calling

oymdgrw7

oymdgrw72#

试试看:

import {
  checkPanoramaFormat
} from '@/common/helpers'

describe('checkPanoramaFormat', () => {
  const panorama = { anotherProp: '1' }

  it('creates clone', () => {
    const result = () => checkPanoramaFormat(panorama)

    expect(result).toThrowError('panorama id is required')
  })
})

字符串

相关问题