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
- using Xunit ;
12
13
using React . Web . Mvc ;
14
+ using Xunit ;
13
15
14
16
namespace React . Tests . Mvc
15
17
{
@@ -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
}
@@ -54,6 +57,61 @@ public void ReactWithInitShouldReturnHtmlAndScript()
54
57
) ;
55
58
}
56
59
60
+ [ Fact ]
61
+ public void ScriptNonceIsReturned ( )
62
+ {
63
+ string nonce ;
64
+ using ( var random = new RNGCryptoServiceProvider ( ) )
65
+ {
66
+ byte [ ] nonceBytes = new byte [ 16 ] ;
67
+ random . GetBytes ( nonceBytes ) ;
68
+ nonce = Convert . ToBase64String ( nonceBytes ) ;
69
+ }
70
+
71
+ var component = new Mock < IReactComponent > ( ) ;
72
+ component . Setup ( x => x . RenderHtml ( false , false , null ) ) . Returns ( "HTML" ) ;
73
+ component . Setup ( x => x . RenderJavaScript ( ) ) . Returns ( "JS" ) ;
74
+
75
+ var config = new Mock < IReactSiteConfiguration > ( ) ;
76
+
77
+ var environment = ConfigureMockEnvironment ( config . Object ) ;
78
+
79
+ environment . Setup ( x => x . Configuration ) . Returns ( config . Object ) ;
80
+ environment . Setup ( x => x . CreateComponent (
81
+ "ComponentName" ,
82
+ new { } ,
83
+ null ,
84
+ false ,
85
+ false
86
+ ) ) . Returns ( component . Object ) ;
87
+
88
+ // without nonce
89
+ var result = HtmlHelperExtensions . ReactWithInit (
90
+ htmlHelper : null ,
91
+ componentName : "ComponentName" ,
92
+ props : new { } ,
93
+ htmlTag : "span"
94
+ ) ;
95
+ Assert . Equal (
96
+ "HTML" + System . Environment . NewLine + "<script>JS</script>" ,
97
+ result . ToString ( )
98
+ ) ;
99
+
100
+ config . Setup ( x => x . ScriptNonceProvider ) . Returns ( ( ) => nonce ) ;
101
+
102
+ // with nonce
103
+ result = HtmlHelperExtensions . ReactWithInit (
104
+ htmlHelper : null ,
105
+ componentName : "ComponentName" ,
106
+ props : new { } ,
107
+ htmlTag : "span"
108
+ ) ;
109
+ Assert . Equal (
110
+ "HTML" + System . Environment . NewLine + "<script nonce=\" " + nonce + "\" >JS</script>" ,
111
+ result . ToString ( )
112
+ ) ;
113
+ }
114
+
57
115
[ Fact ]
58
116
public void EngineIsReturnedToPoolAfterRender ( )
59
117
{
0 commit comments