Testing React Native Image.getSize: Cannot spyOn on a primitive value; string given

559 Views Asked by At

I have a hook that detects the orientation of a React Native Image:

import { useState, useEffect } from 'react'
import { Image } from 'react-native'

const useFindImageSize = (image) => {
  const [width, setWidth] = useState(0)
  const [height, setHeight] = useState(0)

  useEffect(() => {
    (async() => {
      await Image.getSize(image,
        (width, height) => {
          setWidth(width)
          setHeight(height)
        })
    })()
  }, [image])

  return { width, height }
}

And have written a test initially to see if getSize has been called:

import { Image } from 'react-native'
import { renderHook } from '@testing-library/react-hooks'
import useFindImageSize from '../useFindImageSize'

describe('useFindImageSize', () => {
  const getSize = jest.spyOn(
    Image, 'getSize').mockImplementation(jest.fn()
  )

  afterEach(() => {
    jest.clearAllMocks()
  })

  it('should call getSize', () => {
    const { result } = renderHook(() =>
      useFindImageSize('test_image')
    )
    expect(getSize).toHaveBeenCalledTimes(1)
  })
})

A basic test which I would've thought would work, (this is based on this question/answer about the same topic).

But I'm getting this error when running my test:

 ● ImageOrientation › useFindImageSize › encountered a declaration exception
Cannot spyOn on a primitive value; string given

Which refers to const getSizeSpyOn = jest.spyOn(

The hook takes an image uri as its argument and then decides whether it should be a portrait or landscape image, but I'm pretty stuck on how to get around this. Anyone know what I'm doing wrong?

1

There are 1 best solutions below

1
On

Try something like:

const getSize = jest.spyOn(Image.prototype, 'getSize')
  .mockImplementation(jest.fn())

Same as your code, with just ".prototype" added (without quotes).