我编写了一个用react 17.0.2构建的组件,该组件使用react-intersection-observer 9.1.0
import { useInView } from 'react-intersection-observer'
...
const [ref, inView] = useInView({
threshold: 0.99,
root: scrollRef.current,
delay: 250,
trackVisibility: true,
onChange: (inView: boolean) => {
onChildInView(index, inView)
}
})若要检测视口内外的滑动行为,请执行以下操作。组件工作得很好。
我使用@testing-library/react 12.1.4和@testing-library/jest-dom 5.16.3编写了一些单元测试,以使组件更安全。
一旦我用下面的代码测试上述组件的存在或可见性
describe('method render', () => {
test('renders correctly', () => {
render(
<MyComponent
props={...}
data-testid="component-id"
>
<div />
<div />
</MyComponent>
)
const componentNode = screen.getByTestId('component-id')
expect(componentNode).toBeInTheDocument()
expect(componentNode).toBeVisible()
})
})测试库会发出消息错误的通知。
ReferenceError: IntersectionObserver is not defined我试图通过在测试顶部模拟库(如链接这里)来修复它。
const intersectionObserverMock = () => ({
observe: () => null
})
declare global {
interface Window {
IntersectionObserver: typeof IntersectionObserver
}
}
window.IntersectionObserver = jest.fn().mockImplementation(intersectionObserverMock);但是它没有工作,因为
TypeError: observer.unobserve is not a function有什么建议吗?遗漏了什么吗?
发布于 2022-05-09 15:05:45
要解决这个问题,我建议使用mockAllIsIntersecting ( test-utils.js in react-intersection-observer )。这个函数模拟IntersectionObserver。
例如:
import { mockAllIsIntersecting } from 'react-intersection-observer/test-utils';
describe('method render', () => {
test('renders correctly', () => {
render(
<MyComponent
props={...}
data-testid="component-id"
>
<div />
<div />
</MyComponent>
)
mockAllIsIntersecting(true)
const componentNode = screen.getByTestId('component-id')
expect(componentNode).toBeInTheDocument()
expect(componentNode).toBeVisible()
})
})https://stackoverflow.com/questions/72154008
复制相似问题