반응형
대응 테스트 라이브러리:useLocation()이 포함된 구성 요소를 테스트하는 방법
나는 레드우드를 사용하고 있다.후드 아래에서 리액션 테스트 라이브러리를 사용하는 JS.useLocation() 후크 때문에 구성요소(및 트리에 이 구성요소가 있는 모든 페이지 구성요소)를 테스트하려고 애쓰고 있다.
사용 시useLocation()
구성 요소 내부 후크, 오류를 방지하기 위해 브라우저 위치 기록을 조롱하는 라우터로 테스트 중인 구성 요소를 포장해야 함Error: Uncaught [TypeError: Cannot read property 'pathname' of undefined]
.
하지만 그렇게 하면 항법 구성요소가 더 이상 완전히 렌더링되지 않아 테스트할 수 없어...무슨 생각 있어?
항법js
//import statements
const renderListItems = (pathname) => {
const NavigationItems = [{..},{..},{..}] // example
return NavigationItems.map((item) => {
const selected = pathname.indexOf(item.path) ? false : true
return (
<ListItem
button
key={item.text}
onClick={() => {
navigate(item.route)
}}
selected={selected}
>
<ListItemText primary={item.text} />
</ListItem>
)
})
}
const Navigation = () => {
const { pathname } = useLocation() // this is why I need to wrap the Navigation component in a router for testing; I'm trying to get the current pathname so that I can give a specific navigation item an active state.
return (
<List data-testid="navigation" disablePadding>
{renderListItems(pathname)}
</List>
)
}
export default Navigation
항법.test.js
import { screen } from '@redwoodjs/testing'
import { renderWithRouter } from 'src/utilities/testHelpers'
import Navigation from './Navigation'
describe('Navigation', () => {
it('renders successfully', () => {
expect(() => {
renderWithRouter(<Navigation />)
}).not.toThrow()
})
it('has a "Dashboard" navigation menu item', () => {
renderWithRouter(<Navigation />)
expect(
screen.getByRole('button', { text: /Dashboard/i })
).toBeInTheDocument()
})
})
테스트 도우미.js
이것은 예방하기 위해 필요하다.useLocation()
내부 항법.js 테스트 위반 방지.
import { Router, Route } from '@redwoodjs/router'
import { createMemoryHistory } from 'history'
import { render } from '@redwoodjs/testing'
const history = createMemoryHistory()
export const renderWithRouter = (Component) =>
render(
<Router history={history}>
<Route component={Component} />
</Router>
)
결과오류
Navigation › has a "Dashboard" navigation menu item
TestingLibraryElementError: Unable to find an accessible element with the role "button"
There are no accessible roles. But there might be some inaccessible roles. If you wish to access them, then set the `hidden` option to `true`. Learn more about this here: https://testing-library.com/docs/dom-testing-library/api-queries#byrole
<body>
<div />
</body>
놀려도 좋다useLocation
원하는 경로 이름을 반환하십시오.이것은 어떤 기능에도 적용될 수 있다.
심플
//Put within testing file
jest.mock("router-package", () => ({
...jest.requireActual("router-package"),
useLocation: () => ({
pathname: "customPath/To/Return"
})
}));
세부적
경로를 통과할 수 있는 도우미 기능을 만들 수 있다(string
) 그리고 그것은 자동적으로 당신을 그렇게 조롱한다.
random.test.js
import { setUpPageRender } from 'src/utilities/testHelpers'
import Navigation from './Navigation'
describe('Navigation', () => {
//Where we set up our custom path for the describe
const render = setUpPageRender('/customPathForThisDescribe/Foo')
it('renders successfully', () => {
expect(() => {
render(<Navigation />)
}).not.toThrow()
})
})
테스트 도우미.js
//Mocked Functions
jest.mock('router-package', () => ({
__esModule: true,
...jest.requireActual('router-package'),
useLocation: jest.fn(),
}))
import { useLocation } from 'router-package'
export const setUpPageRender = (location) => {
useLocation.mockReturnValue(location)
beforeEach(() => {
jest.clearAllMocks()
})
return (component) => {
return render( <Router history={history}>
<Route component={Component} />
</Router>)
}
}
반응형
'Programing' 카테고리의 다른 글
어떤 방법으로 VueJS 구성 요소를 파괴하는 방법? (0) | 2022.03.29 |
---|---|
왜 Python은 제곱근에 대해 "잘못된" 대답을 하는가?파이썬 2의 정수분할이란? (0) | 2022.03.29 |
python Simple을 실행할 수 있는가?로컬 호스트에서만 HTTPServer를 사용하시겠습니까? (0) | 2022.03.29 |
Vue.js—v-model과 v-bind의 차이 (0) | 2022.03.28 |
Python 2.x의 nonlocal 키워드 (0) | 2022.03.28 |