|
1 | 1 | import { render, screen } from '@testing-library/react'; |
2 | 2 |
|
| 3 | +import { VERSION_SUPPORT_SHORTCUT } from '@/next.constants.mjs'; |
| 4 | + |
3 | 5 | import ActiveLink from '..'; |
4 | 6 |
|
| 7 | +// mock usePathname, but retain all the other imports |
| 8 | +jest.mock('@/navigation.mjs', () => ({ |
| 9 | + ...jest.requireActual('@/navigation.mjs'), |
| 10 | + usePathname: jest.fn(), |
| 11 | +})); |
| 12 | + |
5 | 13 | describe('ActiveLink', () => { |
6 | 14 | it('renders as localized link', () => { |
7 | 15 | render( |
@@ -38,4 +46,61 @@ describe('ActiveLink', () => { |
38 | 46 | 'link active' |
39 | 47 | ); |
40 | 48 | }); |
| 49 | + |
| 50 | + it('does not set active class when href base does not match', () => { |
| 51 | + const { usePathname } = require('@/navigation.mjs'); |
| 52 | + usePathname.mockReturnValue('/not-link/sublink'); |
| 53 | + |
| 54 | + render( |
| 55 | + <ActiveLink |
| 56 | + className="link" |
| 57 | + activeClassName="active" |
| 58 | + allowSubPath={true} |
| 59 | + href={'/link/sub-link'} |
| 60 | + > |
| 61 | + Link |
| 62 | + </ActiveLink> |
| 63 | + ); |
| 64 | + |
| 65 | + expect(screen.findByText('Link')).resolves.toHaveAttribute('class', 'link'); |
| 66 | + }); |
| 67 | + |
| 68 | + it('sets active class when href is other than VERSION_SUPPORT_SHORTCUT', () => { |
| 69 | + const { usePathname } = require('@/navigation.mjs'); |
| 70 | + usePathname.mockReturnValue('/link/sublink'); |
| 71 | + |
| 72 | + render( |
| 73 | + <ActiveLink |
| 74 | + className="link" |
| 75 | + activeClassName="active" |
| 76 | + allowSubPath={true} |
| 77 | + href={'/link/sub-link'} |
| 78 | + > |
| 79 | + Link |
| 80 | + </ActiveLink> |
| 81 | + ); |
| 82 | + |
| 83 | + expect(screen.findByText('Link')).resolves.toHaveAttribute( |
| 84 | + 'class', |
| 85 | + 'link active' |
| 86 | + ); |
| 87 | + }); |
| 88 | + |
| 89 | + it('does not set active class when href is VERSION_SUPPORT_SHORTCUT', () => { |
| 90 | + const { usePathname } = require('@/navigation.mjs'); |
| 91 | + usePathname.mockReturnValue(VERSION_SUPPORT_SHORTCUT); |
| 92 | + |
| 93 | + render( |
| 94 | + <ActiveLink |
| 95 | + className="link" |
| 96 | + activeClassName="active" |
| 97 | + allowSubPath={true} |
| 98 | + href={VERSION_SUPPORT_SHORTCUT} |
| 99 | + > |
| 100 | + Link |
| 101 | + </ActiveLink> |
| 102 | + ); |
| 103 | + |
| 104 | + expect(screen.findByText('Link')).resolves.toHaveAttribute('class', 'link'); |
| 105 | + }); |
41 | 106 | }); |
0 commit comments