|
| 1 | +import { describe, expect, it } from 'vitest' |
| 2 | + |
| 3 | +import { colorlessConfig } from '../colorConfig' |
| 4 | +import { PrintContext } from '../printContext' |
| 5 | +import { StringFormatter } from './formatter' |
| 6 | + |
| 7 | +const makeCtx = ( |
| 8 | + overrides: Partial<Pick<PrintContext, 'quotes'>> = {} |
| 9 | +): PrintContext => ({ |
| 10 | + indent: '', |
| 11 | + maxIndent: 10, |
| 12 | + indentString: ' ', |
| 13 | + colorConfig: colorlessConfig, |
| 14 | + seen: new WeakSet(), |
| 15 | + quotes: overrides.quotes ?? '"', |
| 16 | + keys: [], |
| 17 | + prefix: '', |
| 18 | +}) |
| 19 | + |
| 20 | +describe('StringFormatter', () => { |
| 21 | + it('escapes double quotes when using double quotes', () => { |
| 22 | + const fmt = new StringFormatter() |
| 23 | + const ctx = makeCtx() |
| 24 | + const value = 'a "quote" b' |
| 25 | + const result = fmt.format(value, ctx) |
| 26 | + const expected = `${ctx.quotes}${value |
| 27 | + .split(ctx.quotes) |
| 28 | + .join(`\\${ctx.quotes}`)}${ctx.quotes}` |
| 29 | + expect(result).toBe(expected) |
| 30 | + }) |
| 31 | + |
| 32 | + it('escapes single quotes when using single quotes', () => { |
| 33 | + const fmt = new StringFormatter() |
| 34 | + const ctx = makeCtx({ quotes: "'" }) |
| 35 | + const value = "a 'quote' b" |
| 36 | + const result = fmt.format(value, ctx) |
| 37 | + const expected = `${ctx.quotes}${value |
| 38 | + .split(ctx.quotes) |
| 39 | + .join(`\\${ctx.quotes}`)}${ctx.quotes}` |
| 40 | + expect(result).toBe(expected) |
| 41 | + }) |
| 42 | + |
| 43 | + it('does not escape when quotes are disabled', () => { |
| 44 | + const fmt = new StringFormatter() |
| 45 | + const ctx = makeCtx({ quotes: '' }) |
| 46 | + const value = 'a "quote" b' |
| 47 | + const result = fmt.format(value, ctx) |
| 48 | + expect(result).toBe(value) |
| 49 | + }) |
| 50 | +}) |
0 commit comments