1

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 Answer 1

0

Try something like:

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for responding! Unfortunately that came back with Cannot spyOn on a primitive value; undefined given.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.