summaryrefslogtreecommitdiff
path: root/src/components/active-link.test.tsx
blob: 0c603cb5f839104dedfc460b3a1a742914c09312 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { render, screen } from '@testing-library/react';
import type { ReactNode } from 'react';
import { describe, expect, test, vi } from 'vitest';
import { ActiveLink } from './active-link';
import { usePathname } from 'next/navigation';

vi.mock('next/navigation', () => ({
  usePathname: vi.fn(),
}));

vi.mock('next/link', () => ({
  default: ({
    href,
    children,
    ...props
  }: {
    href: string;
    children: ReactNode;
  }) => (
    <a href={href} {...props}>
      {children}
    </a>
  ),
}));

describe('ActiveLink', () => {
  test('applies active styles when pathname matches href', () => {
    vi.mocked(usePathname).mockReturnValue('/posts');

    render(<ActiveLink href='/posts'>Posts</ActiveLink>);

    const link = screen.getByRole('link', { name: 'Posts' });
    expect(link).toHaveClass('font-medium');
  });

  test('does not apply active styles for non-matching paths', () => {
    vi.mocked(usePathname).mockReturnValue('/tags');

    render(<ActiveLink href='/posts'>Posts</ActiveLink>);

    const link = screen.getByRole('link', { name: 'Posts' });
    expect(link).not.toHaveClass('font-medium');
  });

  test('supports nested path matching when nested prop is enabled', () => {
    vi.mocked(usePathname).mockReturnValue('/posts/testing-vitest');

    render(
      <ActiveLink href='/posts' nested>
        Posts
      </ActiveLink>,
    );

    const link = screen.getByRole('link', { name: 'Posts' });
    expect(link).toHaveClass('font-medium');
  });
});