7
7
* of patent rights can be found in the PATENTS file in the same directory.
8
8
*/
9
9
10
+ using System ;
11
+ using System . Security . Cryptography ;
10
12
using Moq ;
11
13
using React . Web . Mvc ;
12
14
using Xunit ;
@@ -20,9 +22,10 @@ public class HtmlHelperExtensionsTests
20
22
/// This is only required because <see cref="HtmlHelperExtensions"/> can not be
21
23
/// injected :(
22
24
/// </summary>
23
- private Mock < IReactEnvironment > ConfigureMockEnvironment ( )
25
+ private Mock < IReactEnvironment > ConfigureMockEnvironment ( IReactSiteConfiguration configuration = null )
24
26
{
25
27
var environment = new Mock < IReactEnvironment > ( ) ;
28
+ environment . Setup ( x => x . Configuration ) . Returns ( configuration ?? new ReactSiteConfiguration ( ) ) ;
26
29
AssemblyRegistration . Container . Register ( environment . Object ) ;
27
30
return environment ;
28
31
}
@@ -53,6 +56,60 @@ public void ReactWithInitShouldReturnHtmlAndScript()
53
56
) ;
54
57
}
55
58
59
+ [ Fact ]
60
+ public void ScriptNonceIsReturned ( )
61
+ {
62
+ string nonce ;
63
+ using ( var random = new RNGCryptoServiceProvider ( ) )
64
+ {
65
+ byte [ ] nonceBytes = new byte [ 16 ] ;
66
+ random . GetBytes ( nonceBytes ) ;
67
+ nonce = Convert . ToBase64String ( nonceBytes ) ;
68
+ }
69
+
70
+ var component = new Mock < IReactComponent > ( ) ;
71
+ component . Setup ( x => x . RenderHtml ( false , false , null ) ) . Returns ( "HTML" ) ;
72
+ component . Setup ( x => x . RenderJavaScript ( ) ) . Returns ( "JS" ) ;
73
+
74
+ var config = new Mock < IReactSiteConfiguration > ( ) ;
75
+
76
+ var environment = ConfigureMockEnvironment ( config . Object ) ;
77
+
78
+ environment . Setup ( x => x . Configuration ) . Returns ( config . Object ) ;
79
+ environment . Setup ( x => x . CreateComponent (
80
+ "ComponentName" ,
81
+ new { } ,
82
+ null ,
83
+ false
84
+ ) ) . Returns ( component . Object ) ;
85
+
86
+ // without nonce
87
+ var result = HtmlHelperExtensions . ReactWithInit (
88
+ htmlHelper : null ,
89
+ componentName : "ComponentName" ,
90
+ props : new { } ,
91
+ htmlTag : "span"
92
+ ) ;
93
+ Assert . Equal (
94
+ "HTML" + System . Environment . NewLine + "<script>JS</script>" ,
95
+ result . ToString ( )
96
+ ) ;
97
+
98
+ config . Setup ( x => x . ScriptNonceProvider ) . Returns ( ( ) => nonce ) ;
99
+
100
+ // with nonce
101
+ result = HtmlHelperExtensions . ReactWithInit (
102
+ htmlHelper : null ,
103
+ componentName : "ComponentName" ,
104
+ props : new { } ,
105
+ htmlTag : "span"
106
+ ) ;
107
+ Assert . Equal (
108
+ "HTML" + System . Environment . NewLine + "<script nonce=\" " + nonce + "\" >JS</script>" ,
109
+ result . ToString ( )
110
+ ) ;
111
+ }
112
+
56
113
[ Fact ]
57
114
public void EngineIsReturnedToPoolAfterRender ( )
58
115
{
0 commit comments