forked from facebookarchive/draft-js
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNonASCIIStringSnapshotSerializer.js
More file actions
51 lines (46 loc) · 1.2 KB
/
NonASCIIStringSnapshotSerializer.js
File metadata and controls
51 lines (46 loc) · 1.2 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
/**
* Copyright 2004-present Facebook. All Rights Reserved.
*
* @emails oncall+ads_integration_management
* @flow strict-local
* @format
*/
'use strict';
const MAX_ASCII_CHARACTER = 127;
/**
* Serializes strings with non-ASCII characters to their Unicode escape
* sequences (eg. \u2022), to avoid hitting this lint rule:
* "Source code should only include printable US-ASCII bytes"
*/
const NonASCIIStringSnapshotSerializer = {
test(val: mixed): boolean {
if (typeof val !== 'string') {
return false;
}
for (let i = 0; i < val.length; i++) {
if (val.charCodeAt(i) > MAX_ASCII_CHARACTER) {
return true;
}
}
return false;
},
print: (val: string): string => {
return (
'"' +
val
.split('')
.map(char => {
const code = char.charCodeAt(0);
return code > MAX_ASCII_CHARACTER
? '\\u' + code.toString(16).padStart(4, '0')
: char;
})
.join('')
// Keep the same behaviour as Jest's regular string snapshot
// serialization, which escapes double quotes.
.replace(/"/g, '\\"') +
'"'
);
},
};
module.exports = NonASCIIStringSnapshotSerializer;