summaryrefslogtreecommitdiff
path: root/spec/javascripts/locale/sprintf_spec.js
blob: 52e903b819f5497f80e486f52eb3c48b82b55701 (plain)
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import sprintf from '~/locale/sprintf';

describe('locale', () => {
  describe('sprintf', () => {
    it('does not modify string without parameters', () => {
      const input = 'No parameters';

      const output = sprintf(input);

      expect(output).toBe(input);
    });

    it('ignores extraneous parameters', () => {
      const input = 'No parameters';

      const output = sprintf(input, { ignore: 'this' });

      expect(output).toBe(input);
    });

    it('ignores extraneous placeholders', () => {
      const input = 'No %{parameters}';

      const output = sprintf(input);

      expect(output).toBe(input);
    });

    it('replaces parameters', () => {
      const input = '%{name} has %{count} parameters';
      const parameters = {
        name: 'this',
        count: 2,
      };

      const output = sprintf(input, parameters);

      expect(output).toBe('this has 2 parameters');
    });

    it('replaces multiple occurrences', () => {
      const input = 'to %{verb} or not to %{verb}';
      const parameters = {
        verb: 'be',
      };

      const output = sprintf(input, parameters);

      expect(output).toBe('to be or not to be');
    });

    it('escapes parameters', () => {
      const input = 'contains %{userContent}';
      const parameters = {
        userContent: '<script>alert("malicious!")</script>',
      };

      const output = sprintf(input, parameters);

      expect(output).toBe('contains &lt;script&gt;alert(&quot;malicious!&quot;)&lt;/script&gt;');
    });

    it('does not escape parameters for escapeParameters = false', () => {
      const input = 'contains %{safeContent}';
      const parameters = {
        safeContent: '<strong>bold attempt</strong>',
      };

      const output = sprintf(input, parameters, false);

      expect(output).toBe('contains <strong>bold attempt</strong>');
    });
  });
});