Jest - testing Link(next/link)

htzpubme  于 11个月前  发布在  Jest
关注(0)|答案(3)|浏览(149)

我正在尝试编写单元测试来确认我的导航链接是否正常工作。我的MainNavigation.js文件:

import Link from 'next/link';

const MainNavigation = () => {
  return (
    <header>
      <div>
        <Link href='/'>The React Parks</Link>
      </div>
      <nav>
        <ul>
          <li>
            <Link href='/all-parks'>All Parks</Link>
          </li>
          <li>
            <Link href='/new-park'>Add a New Park</Link>
          </li>
        </ul>
      </nav>
    </header>
  )
};

export default MainNavigation;

字符串
我的测试文件:

import '@testing-library/jest-dom'
import { fireEvent, render, screen } from '@testing-library/react';
import MainNavigation from './MainNavigation';

describe('MainNavigation', () => {
    describe('links', () => {
    jest.mock('next/link', () => ({ children }) => children);

    it('should redirect to '/' when clicking on "The React Parks" text', () => {
      render(<MainNavigation />);

      const parksString = screen.getByText('The React Parks');
      fireEvent.click(parksString);
      expect(parksString.closest('link')).toHaveAttribute('href', 'https://');
    })
  });
});


我怎么可能包括检查URL是否匹配某些字符串?或者做一些事情有意义吗?比如分配一个常量来呈现不同的页面,并期望该常量匹配其他页面上的某些文本?如何测试这个功能?

vu8f3i0k

vu8f3i0k1#

我解决了这个问题,

jest.mock(
  'next/link',
  () =>
    ({ children, ...rest }: { children: ReactElement }) =>
      React.cloneElement(children, { ...rest }),
);

字符串
这样,next/linkpush函数就不会失败,并且来自next/linkhref会传递给子组件

a1o7rhls

a1o7rhls2#

我没有得到回复,但我通过使用快照进行测试实现了我想要的:

describe('Links', () => {
    const links = [
      <Link href='/'>The React Parks</Link>,
      <Link href='/all-parks'>All Parks</Link>,
      <<Link href='/new-park'>Add a New Park</Link>
    ]
    it('render correctly', () => {
      const tree = renderer.create(links).toJSON();

      expect(tree).toMatchSnapshot();
    });
  });

字符串

ogsagwnx

ogsagwnx3#

jest.mock('next/link', () => props => require('react').createElement('div', props))

字符串

相关问题