我有一个钩子可以检测 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 }
}
并最初编写了一个测试以查看是否getSize
已调用:
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)
})
})
我认为会起作用的基本测试(这是基于关于同一主题的这个问题/答案)。
但是在运行测试时出现此错误:
● ImageOrientation › useFindImageSize › encountered a declaration exception
Cannot spyOn on a primitive value; string given
指的是const getSizeSpyOn = jest.spyOn(
该钩子将图像 uri 作为其参数,然后决定它应该是肖像还是风景图像,但我很困惑如何解决这个问题。有人知道我在做什么错吗?