2024-02-17 22:53:36 +01:00
|
|
|
/* eslint-env jest */
|
|
|
|
|
2025-02-14 07:43:08 -08:00
|
|
|
import { parseInternalLinks, isMisleadingLink } from './url.js'
|
2024-02-17 22:53:36 +01:00
|
|
|
|
2025-02-14 07:43:08 -08:00
|
|
|
const internalLinkCases = [
|
2024-02-17 22:53:36 +01:00
|
|
|
['https://stacker.news/items/123', '#123'],
|
|
|
|
['https://stacker.news/items/123/related', '#123/related'],
|
|
|
|
// invalid links should not be parsed so user can spot error
|
|
|
|
['https://stacker.news/items/123foobar', undefined],
|
2024-04-09 15:44:45 -04:00
|
|
|
// Invalid origin should not be parsed so no malicious links
|
|
|
|
['https://example.com/items/123', undefined],
|
2024-02-17 22:53:36 +01:00
|
|
|
// parse referral links
|
|
|
|
['https://stacker.news/items/123/r/ekzyis', '#123'],
|
|
|
|
// use comment id if available
|
|
|
|
['https://stacker.news/items/123?commentId=456', '#456'],
|
|
|
|
// comment id + referral link
|
|
|
|
['https://stacker.news/items/123/r/ekzyis?commentId=456', '#456'],
|
|
|
|
// multiple params
|
|
|
|
['https://stacker.news/items/123?commentId=456&parentId=789', '#456']
|
|
|
|
]
|
|
|
|
|
|
|
|
describe('internal links', () => {
|
2025-02-14 07:43:08 -08:00
|
|
|
test.each(internalLinkCases)(
|
2024-02-17 22:53:36 +01:00
|
|
|
'parses %p as %p',
|
|
|
|
(href, expected) => {
|
2024-04-09 15:44:45 -04:00
|
|
|
process.env.NEXT_PUBLIC_URL = 'https://stacker.news'
|
2024-06-03 21:54:42 -05:00
|
|
|
const { linkText: actual } = parseInternalLinks(href)
|
2024-02-17 22:53:36 +01:00
|
|
|
expect(actual).toBe(expected)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
})
|
2025-02-14 07:43:08 -08:00
|
|
|
|
|
|
|
const misleadingLinkCases = [
|
|
|
|
// if text is the same as the link, it's not misleading
|
|
|
|
['https://stacker.news/items/1234', 'https://stacker.news/items/1234', false],
|
|
|
|
// same origin is not misleading
|
|
|
|
['https://stacker.news/items/1235', 'https://stacker.news/items/1234', false],
|
|
|
|
['www.google.com', 'https://www.google.com', false],
|
|
|
|
['stacker.news', 'https://stacker.news', false],
|
|
|
|
// if text is obviously not a link, it's not misleading
|
|
|
|
['innocent text', 'https://stacker.news/items/1234', false],
|
|
|
|
['innocenttext', 'https://stacker.news/items/1234', false],
|
|
|
|
// if text might be a link to a different origin, it's misleading
|
|
|
|
['innocent.text', 'https://stacker.news/items/1234', true],
|
|
|
|
['https://google.com', 'https://bing.com', true],
|
|
|
|
['www.google.com', 'https://bing.com', true],
|
|
|
|
['s-tacker.news', 'https://snacker.news', true]
|
|
|
|
]
|
|
|
|
|
|
|
|
describe('misleading links', () => {
|
|
|
|
test.each(misleadingLinkCases)(
|
|
|
|
'identifies [%p](%p) as misleading: %p',
|
|
|
|
(text, href, expected) => {
|
|
|
|
const actual = isMisleadingLink(text, href)
|
|
|
|
expect(actual).toBe(expected)
|
|
|
|
}
|
|
|
|
)
|
|
|
|
})
|