-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathoptions.fixJSONCtlChars.test.ts
More file actions
60 lines (55 loc) · 1.88 KB
/
options.fixJSONCtlChars.test.ts
File metadata and controls
60 lines (55 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { strict as assert } from 'node:assert';
import { describe, it, beforeAll, afterAll } from 'vitest';
import urllib from '../src/index.js';
import { startServer } from './fixtures/server.js';
describe('options.fixJSONCtlChars.test.ts', () => {
let close: any;
let _url: string;
beforeAll(async () => {
const { closeServer, url } = await startServer();
close = closeServer;
_url = url;
});
afterAll(async () => {
await close();
});
it('should auto fix json control characters when fixJSONCtlChars = true', async () => {
const response = await urllib.request(`${_url}json_with_controls_unicode`, {
dataType: 'json',
fixJSONCtlChars: true,
});
assert.equal(response.status, 200);
// console.log(response.data);
assert.deepEqual(response.data, {
foo: '\b\f\n\r\tbar\u000e!1!\u0086!2!\u0000!3!\u001f!4!\\\!5!end\\\\',
});
});
it('should throw error when json control characters exists', async () => {
await assert.rejects(async () => {
await urllib.request(`${_url}json_with_controls_unicode`, {
dataType: 'json',
});
}, (err: any) => {
assert.equal(err.name, 'JSONResponseFormatError');
// console.error(err);
// JSON parse new message format on Node.js >= 19
assert.match(err.message, /Unexpected token|Bad control character in string literal in JSON at position 8/);
assert.equal(err.status, 200);
assert.equal(err.headers['x-method'], 'GET');
return true;
});
});
it('should fix json string with custom function', async () => {
const response = await urllib.request(`${_url}json_with_t`, {
dataType: 'json',
fixJSONCtlChars(str) {
return str.replace(/\t/g, '\\t');
},
});
assert.equal(response.status, 200);
// console.log(response.data);
assert.deepEqual(response.data, {
foo: 'ba\tr\t\t',
});
});
});