在React中测试在onClick之后获得页面重定向的next/link (Next.js),可以按照以下步骤进行:
YourComponent.test.js
,其中YourComponent
是你要测试的组件名称。import { render, fireEvent } from '@testing-library/react';
import YourComponent from './YourComponent';
render
函数渲染组件,并模拟点击事件:test('should redirect after onClick', () => {
const { getByText } = render(<YourComponent />);
const button = getByText('Click Me');
fireEvent.click(button);
});
fireEvent.click
模拟点击事件后,可以通过断言来验证页面是否发生了重定向。由于你在测试中使用了next/link
组件,可以使用jest.mock
来模拟next/link
的行为:import { useRouter } from 'next/router';
jest.mock('next/router', () => ({
useRouter: jest.fn(),
}));
test('should redirect after onClick', () => {
const pushMock = jest.fn();
useRouter.mockImplementation(() => ({
push: pushMock,
}));
const { getByText } = render(<YourComponent />);
const button = getByText('Click Me');
fireEvent.click(button);
expect(pushMock).toHaveBeenCalledWith('/your-redirect-url');
});
在上述代码中,我们使用jest.mock
来模拟next/router
的行为,并使用useRouter
来返回一个包含push
函数的对象。然后,我们使用pushMock
来验证push
函数是否被调用,并传递了正确的重定向URL。
总结:以上是在React中测试在onClick之后获得页面重定向的next/link (Next.js)的方法。在测试中,我们使用了Jest和React Testing Library来模拟点击事件和验证页面重定向。通过模拟next/link
的行为,我们可以测试组件在点击事件后是否正确地进行页面重定向。
领取专属 10元无门槛券
手把手带您无忧上云