测试 React Native Image.getSize:无法监视原始值;给定的字符串
我有一个钩子可以检测 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
Whichrefers to const getSizeSpyOn = jest.spyOn(
该钩子将图像 uri 作为其参数,然后决定它应该是纵向还是横向图像,但我很困惑如何解决这个问题,有人知道我做错了什么吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试类似的方法:
Try something like: