fix: 🐛 解决多行文本在出码的时候生成的字符串是无效代码的问题

This commit is contained in:
牧毅 2020-11-11 16:13:58 +08:00
parent 19537aad22
commit fa688577e0
2 changed files with 22 additions and 1 deletions

View File

@ -34,7 +34,8 @@ function generateObject(value: CompositeObject, scope: IScope, options: Composit
}
function generateString(value: string): string {
return `'${value}'`;
// 有的字符串里面会有特殊字符,比如换行或引号之类的,这里我们借助 JSON 的字符串转义功能来做下转义并加上双引号
return JSON.stringify(value);
}
function generateNumber(value: number): string {

View File

@ -0,0 +1,20 @@
import test from 'ava';
import { generateCompositeType } from '../../src/utils/compositeType';
import Scope from '../../src/utils/Scope';
test('single line string', (t) => {
t.is(generateCompositeType('ab c', Scope.createRootScope()), '"ab c"');
});
test('multi line string', (t) => {
t.is(generateCompositeType('a\nb\nc', Scope.createRootScope()), '"a\\nb\\nc"');
});
test('string with single quote', (t) => {
t.is(generateCompositeType('a\'bc', Scope.createRootScope()), '"a\'bc"');
});
test('string with double quote', (t) => {
t.is(generateCompositeType('a"bc', Scope.createRootScope()), '"a\\"bc"');
});