Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't the following expect ... toThrowError logging anything in my terminal?

I have a helper that just throws an error:

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

This is my test:

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

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

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

I expected the terminal to show me what was expected and what I got. But I got nothing. In fact, Jest isn't telling me anything:

enter image description here

Why is this and how to fix it?

like image 861
alex Avatar asked Apr 12 '18 02:04

alex


1 Answers

Try instead:

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

If you call the function immediately as the expect argument, it will throw the exception before the assertion. It is not inside a try/catch block. You should instead pass a function handler to expect to be called only on assertion. I enclosed it in an arrow function, but it can be called other forms such as:

expect(myFunc) // no arguments
expect(myFunc.bind(this, arg1, arg2)) // using .bind to set arguments for later calling
like image 74
Andre Figueiredo Avatar answered Oct 03 '22 21:10

Andre Figueiredo