Skip to content

Commit c9d3925

Browse files
authored
Add more tests for helpers (#144)
Regression tests for 357d7ba The FakeRequest object is modeled after the one used for similar tests for the Rails asset tags https://github.com/rails/rails/blob/9994d38bc6c1a8662e510d26c0e9ca8c24ab1189/actionview/test/template/asset_tag_helper_test.rb#L27
1 parent fa5b49a commit c9d3925

File tree

2 files changed

+40
-2
lines changed

2 files changed

+40
-2
lines changed

app/helpers/importmap/importmap_tags_helper.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ def javascript_inline_importmap_tag(importmap_json = Rails.application.importmap
2020
# Configure es-modules-shim with nonce support if the application is using a content security policy.
2121
def javascript_importmap_shim_nonce_configuration_tag
2222
if request&.content_security_policy
23-
tag.script({ nonce: content_security_policy_nonce }.to_json.html_safe,
24-
type: "esms-options", nonce: content_security_policy_nonce)
23+
tag.script({ nonce: request.content_security_policy_nonce }.to_json.html_safe,
24+
type: "esms-options", nonce: request.content_security_policy_nonce)
2525
end
2626
end
2727

test/importmap_tags_helper_test.rb

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,24 @@
11
require "test_helper"
22

33
class Importmap::ImportmapTagsHelperTest < ActionView::TestCase
4+
attr_reader :request
5+
6+
class FakeRequest
7+
def initialize(nonce = nil)
8+
@nonce = nonce
9+
end
10+
11+
def send_early_hints(links); end
12+
13+
def content_security_policy
14+
Object.new if @nonce
15+
end
16+
17+
def content_security_policy_nonce
18+
@nonce
19+
end
20+
end
21+
422
test "javascript_importmap_tags with and without shim" do
523
assert_match /shim/, javascript_importmap_tags("application")
624
assert_no_match /shim/, javascript_importmap_tags("application", shim: false)
@@ -17,4 +35,24 @@ class Importmap::ImportmapTagsHelperTest < ActionView::TestCase
1735
%(<link rel="modulepreload" href="https://cdn.skypack.dev/md5">),
1836
javascript_importmap_module_preload_tags
1937
end
38+
39+
test "tags have no nonce if CSP is not configured" do
40+
@request = FakeRequest.new
41+
42+
assert_no_match /nonce/, javascript_importmap_tags("application")
43+
ensure
44+
@request = nil
45+
end
46+
47+
test "tags have nonce if CSP is configured" do
48+
@request = FakeRequest.new("iyhD0Yc0W+c=")
49+
50+
assert_match /nonce="iyhD0Yc0W\+c="/, javascript_inline_importmap_tag
51+
assert_match /nonce="iyhD0Yc0W\+c="/, javascript_importmap_shim_nonce_configuration_tag
52+
assert_match /nonce="iyhD0Yc0W\+c="/, javascript_importmap_shim_tag
53+
assert_match /nonce="iyhD0Yc0W\+c="/, javascript_import_module_tag("application")
54+
assert_match /nonce="iyhD0Yc0W\+c="/, javascript_importmap_module_preload_tags
55+
ensure
56+
@request = nil
57+
end
2058
end

0 commit comments

Comments
 (0)