Bon*_*teq 3 next.js cypress cypress-component-test-runner
我的导航栏组件依赖于useRouter
提供的功能nextjs/router
来设置活动链接的样式。
我正在尝试使用 Cypress 测试这种行为,但我不确定应该如何组织它。赛普拉斯似乎不喜欢getRoutePathname()
,并且在我的测试环境中返回了未定义。
这是我要测试的组件:
import Link from 'next/link'
import { useRouter } from 'next/router'
function getRoutePathname() {
const router = useRouter()
return router.pathname
}
const Navbar = props => {
const pathname = getRoutePathname()
return (
<nav>
<div className="mr-auto">
<h1>Cody Bontecou</h1>
</div>
{props.links.map(link => (
<Link key={link.to} href={link.to}>
<a
className={`border-transparent border-b-2 hover:border-blue-ninja
${pathname === link.to ? 'border-blue-ninja' : ''}`}
>
{link.text}
</a>
</Link>
))}
</nav>
)
}
export default Navbar
Run Code Online (Sandbox Code Playgroud)
我有 Cypress 组件测试运行程序的骨架设置,并且在硬编码时能够加载组件pathname
,但是一旦我依赖useRouter
,测试运行程序就不再高兴。
import { mount } from '@cypress/react'
import Navbar from '../../component/Navbar'
const LINKS = [
{ text: 'Home', to: '/' },
{ text: 'About', to: '/about' },
]
describe('<Navbar />', () => {
it('displays links', () => {
mount(<Navbar links={LINKS} />)
})
})
Run Code Online (Sandbox Code Playgroud)
小智 7
自最初发布以来,Cypress 添加了一些有关组件测试 NextJs 的更好文档。
\n具体在路由器上自定义您的 Next.js 测试体验,这就是示例(简化)
\n如果将其添加到自定义nextMountWithStubbedRoutes()
命令中,则可以在任何规范中使用它。
Cypress.Commands.add(\'nextMountWithStubbedRoutes\', (component, options) => {\n const router = {\n route: \'/\',\n pathname: \'/\',\n query: {},\n asPath: \'/\',\n basePath: \'\',\n back: cy.stub().as(\'router:back\'),\n forward: cy.stub().as(\'router:forward\'),\n push: cy.stub().as(\'router:push\'),\n reload: cy.stub().as(\'router:reload\'),\n replace: cy.stub().as(\'router:replace\'),\n isReady: true,\n ...(options?.router || {}),\n }\n\n return mount(\n <RouterContext.Provider value={router}>\n {component}\n </RouterContext.Provider>,\n options\n )\n})\n
Run Code Online (Sandbox Code Playgroud)\n请参阅警告:
\n\n\n不幸的是,没有免费的午餐。将这些额外的项目添加到每个安装中会影响性能并在组件的边界之外引入全局状态元素。您可以根据您的用例来决定这些权衡是否值得。
\n
鉴于此警告,请使用特定的nextMountWithStubbedRoutes()
仅在需要它的测试中使用特定的。
归档时间: |
|
查看次数: |
2182 次 |
最近记录: |