Files
glchat/web/tests/links.test.ts
T

80 lines
3.6 KiB
TypeScript
Raw Normal View History

import { describe, expect, it } from 'vitest';
import { firstLink } from '@/lib/links';
/**
* Первая ссылка сообщения: markdown-разметка, «голые» адреса и всё, что
* превьюшить нельзя, — код, чужие схемы, хвостовая пунктуация.
*/
describe('firstLink', () => {
it('находит адрес в markdown-ссылке', () => {
expect(firstLink('смотри [документацию](https://example.com/docs) там')).toBe(
'https://example.com/docs',
);
});
it('находит «голую» ссылку', () => {
expect(firstLink('новость тут https://example.com/news и всё')).toBe(
'https://example.com/news',
);
expect(firstLink('http://example.com')).toBe('http://example.com');
});
it('возвращает первую ссылку и не смотрит на следующие', () => {
expect(firstLink('https://one.example и https://two.example')).toBe('https://one.example');
expect(firstLink('первая строка\nhttps://second.example')).toBe('https://second.example');
});
it('в `[https://a](https://b)` берёт адрес разметки, а не текст ссылки', () => {
expect(firstLink('[https://текст.example](https://цель.example)')).toBe('https://цель.example');
});
it('пропускает блок кода', () => {
expect(firstLink('```\nhttps://code.example\n```')).toBeNull();
expect(firstLink('```bash\ncurl https://code.example\n```\nа вот https://real.example')).toBe(
'https://real.example',
);
});
it('пропускает инлайновый код', () => {
expect(firstLink('`https://code.example`')).toBeNull();
expect(firstLink('в примере `https://code.example`, а живьём https://real.example')).toBe(
'https://real.example',
);
});
it('находит ссылку в цитате', () => {
expect(firstLink('> https://quoted.example')).toBe('https://quoted.example');
});
it('обрезает хвостовую пунктуацию', () => {
expect(firstLink('ссылка https://example.com/page.')).toBe('https://example.com/page');
expect(firstLink('ссылка https://example.com/page, и ещё')).toBe('https://example.com/page');
expect(firstLink('«https://example.com/page»')).toBe('https://example.com/page');
expect(firstLink('что это: https://example.com/page?!')).toBe('https://example.com/page');
});
it('обрезает markdown-обёртки', () => {
expect(firstLink('**https://example.com/bold**')).toBe('https://example.com/bold');
expect(firstLink('~~https://example.com/strike~~')).toBe('https://example.com/strike');
expect(firstLink('_https://example.com/italic_')).toBe('https://example.com/italic');
});
it('не считает ссылкой адрес без хоста', () => {
expect(firstLink('просто https://')).toBeNull();
expect(firstLink('просто https://.')).toBeNull();
});
it('игнорирует другие схемы', () => {
expect(firstLink('ftp://example.com/file.txt')).toBeNull();
expect(firstLink('javascript:alert(1)')).toBeNull();
expect(firstLink('mailto:user@example.com')).toBeNull();
expect(firstLink('[клик](javascript:alert(1))')).toBeNull();
});
it('возвращает null, если ссылки нет', () => {
expect(firstLink('обычный текст без адресов')).toBeNull();
expect(firstLink('')).toBeNull();
});
});