返回 slidev
utils.test.ts
根目录 / packages / slidev / node / utils.test.ts
1 import type { Connect } from 'vite'
2 import { Buffer } from 'node:buffer'
3 import { Readable } from 'node:stream'
4 import { describe, expect, it } from 'vitest'
5 import { applyNotesAutoRuby, getBodyJson, isPathInsideRoots } from './utils'
6
7 describe('isPathInsideRoots', () => {
8 it('accepts a path nested inside a root', () => {
9 expect(isPathInsideRoots('/a/b/c', ['/a'])).toBe(true)
10 })
11
12 it('accepts a path that equals the root itself', () => {
13 expect(isPathInsideRoots('/a', ['/a'])).toBe(true)
14 })
15
16 it('rejects a path outside every root', () => {
17 expect(isPathInsideRoots('/x', ['/a'])).toBe(false)
18 })
19
20 it('rejects a `..`-escaping relative resolution', () => {
21 expect(isPathInsideRoots('/a/../x', ['/a'])).toBe(false)
22 })
23
24 it('accepts when any of several roots contains the path', () => {
25 expect(isPathInsideRoots('/b/c', ['/a', '/b'])).toBe(true)
26 })
27 })
28
29 describe('applyNotesAutoRuby', () => {
30 it('wraps a matched key in a ruby tag', () => {
31 expect(applyNotesAutoRuby('私は勉強しています。', { 勉強: 'べんきょう' }))
32 .toBe('私は<ruby>勉強<rt>べんきょう</rt></ruby>しています。')
33 })
34
35 it('prefers the longest key when one key starts with another', () => {
36 expect(applyNotesAutoRuby('私は日本語を話す', { 日本: 'ni hon', 日本語: 'ni hon go' }))
37 .toBe('私は<ruby>日本語<rt>ni hon go</rt></ruby>を話す')
38 })
39
40 it('matches keys containing regular expression characters literally', () => {
41 expect(applyNotesAutoRuby('I write C++ code', { 'C++': 'see plus plus' }))
42 .toBe('I write <ruby>C++<rt>see plus plus</rt></ruby> code')
43 expect(applyNotesAutoRuby('the (foo) case', { '(foo)': 'ふー' }))
44 .toBe('the <ruby>(foo)<rt>ふー</rt></ruby> case')
45 })
46
47 it('only matches whole words for alphanumeric keys', () => {
48 expect(applyNotesAutoRuby('slidev slidevjs', { slidev: 'slide dev' }))
49 .toBe('<ruby>slidev<rt>slide dev</rt></ruby> slidevjs')
50 })
51
52 it('returns the input untouched when there is no key', () => {
53 expect(applyNotesAutoRuby('unchanged', {})).toBe('unchanged')
54 })
55 })
56
57 describe('getBodyJson', () => {
58 function request(...chunks: Buffer[]) {
59 return Readable.from(chunks, { objectMode: false }) as Connect.IncomingMessage
60 }
61
62 it('parses a body that is split inside a character', async () => {
63 const body = Buffer.from(JSON.stringify({ note: '日本語' }))
64 for (let i = 1; i < body.length; i++) {
65 expect(await getBodyJson(request(body.subarray(0, i), body.subarray(i))))
66 .toEqual({ note: '日本語' })
67 }
68 })
69
70 it('rejects a body that is not JSON', async () => {
71 await expect(getBodyJson(request(Buffer.from('{')))).rejects.toThrow(SyntaxError)
72 })
73 })
74
74 lines TYPESCRIPT