summaryrefslogtreecommitdiff
path: root/spec/helpers/gitlab_script_tag_helper_spec.rb
blob: 37413b9b1c273a25386aaa8ec074d9c383bba9c0 (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
# frozen_string_literal: true

require 'spec_helper'

RSpec.describe GitlabScriptTagHelper do
  before do
    allow(helper).to receive(:content_security_policy_nonce).and_return('noncevalue')
  end

  describe 'external script tag' do
    let(:script_url) { 'test.js' }

    it 'returns a script tag with defer=true and a nonce' do
      expect(helper.javascript_include_tag(script_url).to_s)
        .to eq "<script src=\"/javascripts/#{script_url}\" defer=\"defer\" nonce=\"noncevalue\"></script>"
    end
  end

  describe 'inline script tag' do
    let(:tag_with_nonce) {"<script nonce=\"noncevalue\">\n//<![CDATA[\nalert(1)\n//]]>\n</script>"}
    let(:tag_with_nonce_and_type) {"<script type=\"application/javascript\" nonce=\"noncevalue\">\n//<![CDATA[\nalert(1)\n//]]>\n</script>"}

    it 'returns a script tag with a nonce using block syntax' do
      expect(helper.javascript_tag { 'alert(1)' }.to_s).to eq tag_with_nonce
    end

    it 'returns a script tag with a nonce using block syntax with options' do
      expect(helper.javascript_tag(type: 'application/javascript') { 'alert(1)' }.to_s).to eq tag_with_nonce_and_type
    end

    it 'returns a script tag with a nonce using argument syntax' do
      expect(helper.javascript_tag('alert(1)').to_s).to eq tag_with_nonce
    end

    it 'returns a script tag with a nonce using argument syntax with options' do
      expect(helper.javascript_tag( 'alert(1)', type: 'application/javascript').to_s).to eq tag_with_nonce_and_type
    end

    # This scenario does not really make sense, but it's supported so we test it
    it 'returns a script tag with a nonce using argument and block syntax with options' do
      expect(helper.javascript_tag( '// ignored', type: 'application/javascript') { 'alert(1)' }.to_s).to eq tag_with_nonce_and_type
    end
  end
end