-
Notifications
You must be signed in to change notification settings - Fork 11.6k
/
SanitizedSVG.test.tsx
58 lines (45 loc) · 2.59 KB
/
SanitizedSVG.test.tsx
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
import { getSvgId, getSvgStyle, svgStyleCleanup } from './utils';
const ID = 'TEST_ID';
const svgNoId =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><style type="text/css">.st0{fill:purple;}</style><circle cx="12" cy="12" r="10" class="st0"/></svg>';
const svgWithId = `<svg id="${ID}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><style type="text/css">.st0{fill:blue;}</style><circle cx="12" cy="12" r="10" class="st0"/></svg>`;
const svgWithWrongIdInStyle =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><style type="text/css">#WRONG .st0{fill:green;}</style><circle cx="12" cy="12" r="10" class="st0"/></svg>';
describe('SanitizedSVG', () => {
it('should cleanup the style and generate an ID', () => {
const cleanStyle = svgStyleCleanup(svgNoId);
const updatedStyle = getSvgStyle(cleanStyle);
const svgId = getSvgId(cleanStyle);
expect(cleanStyle.indexOf('id="')).toBeGreaterThan(-1);
expect(svgId).toBeDefined();
expect(svgId?.startsWith('x')).toBeTruthy();
expect(updatedStyle?.indexOf(`#${svgId}`)).toBeGreaterThan(-1);
expect(cleanStyle).toEqual(
`<svg id="${svgId}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><style type="text/css">#${svgId} .st0{fill:purple;}</style><circle cx="12" cy="12" r="10" class="st0"/></svg>`
);
});
it('should cleanup the style and use the existing ID', () => {
const cleanStyle = svgStyleCleanup(svgWithId);
const updatedStyle = getSvgStyle(cleanStyle);
const svgId = getSvgId(cleanStyle);
expect(cleanStyle.indexOf('id="')).toBeGreaterThan(-1);
expect(svgId).toBeDefined();
expect(svgId).toEqual(ID);
expect(updatedStyle?.indexOf(`#${svgId}`)).toBeGreaterThan(-1);
expect(cleanStyle).toEqual(
`<svg id="${svgId}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><style type="text/css">#${svgId} .st0{fill:blue;}</style><circle cx="12" cy="12" r="10" class="st0"/></svg>`
);
});
it('should cleanup the style and replace the wrong ID', () => {
const cleanStyle = svgStyleCleanup(svgWithWrongIdInStyle);
const updatedStyle = getSvgStyle(cleanStyle);
const svgId = getSvgId(cleanStyle);
expect(cleanStyle.indexOf('id="')).toBeGreaterThan(-1);
expect(svgId).toBeDefined();
expect(svgId?.startsWith('x')).toBeTruthy();
expect(updatedStyle?.indexOf(`#${svgId}`)).toBeGreaterThan(-1);
expect(cleanStyle).toEqual(
`<svg id="${svgId}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><style type="text/css">#${svgId} .st0{fill:green;}</style><circle cx="12" cy="12" r="10" class="st0"/></svg>`
);
});
});