javascript - 为什么以下 expect ... toThrowError 没有在我的终端中记录任何内容?

标签 javascript jestjs

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

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 没有告诉我任何事情:

enter image description here

这是为什么以及如何解决?

最佳答案

改为尝试:

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

如果您立即将函数作为 expect 参数调用,它将在断言之前抛出异常。它不在 try/catch block 内。您应该改为将函数处理程序传递给 expect 以仅在断言时调用。我把它封装在一个箭头函数中,但它可以调用其他形式如:

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

关于javascript - 为什么以下 expect ... toThrowError 没有在我的终端中记录任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49787160/

相关文章:

node.js - Jest 模拟和测试 require.resolve 调用

javascript - 为 socket.io 导出 HTTP 服务器不起作用

javascript - 使用jQuery按下回车键时单击链接

reactjs - 开 Jest 如何用全局变量覆盖所有分支

unit-testing - 使用 Vue.js 和 Jest 进行 URL 重定向测试

node.js - 如何使用 Jest 断言数据类型

javascript - 触发自定义 jquery 单击 Angular 自定义指令

javascript - 如何在我的 cordova 应用程序中点赞 Facebook 页面?

javascript - 将 SeqeunceJS 与 Twitter Bootstrap 3.0 集成

javascript - 开 Jest 测试: Awating multiple promises in connected component