|
| 1 | +// Copyright (c) .NET Foundation. All rights reserved. |
| 2 | +// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. |
| 3 | + |
| 4 | +using System.Collections.Generic; |
| 5 | +using Microsoft.AspNetCore.SpaServices.Prerendering; |
| 6 | +using Newtonsoft.Json; |
| 7 | +using Newtonsoft.Json.Linq; |
| 8 | +using Xunit; |
| 9 | + |
| 10 | +namespace Microsoft.AspNetCore.SpaServices.Tests |
| 11 | +{ |
| 12 | + public class RenderToStringResultTest |
| 13 | + { |
| 14 | + [Fact] |
| 15 | + public void HandlesNullGlobals() |
| 16 | + { |
| 17 | + // Arrange |
| 18 | + var renderToStringResult = new RenderToStringResult(); |
| 19 | + renderToStringResult.Globals = null; |
| 20 | + |
| 21 | + // Act |
| 22 | + var actualScript = renderToStringResult.CreateGlobalsAssignmentScript(); |
| 23 | + |
| 24 | + // Assert |
| 25 | + Assert.Equal(string.Empty, actualScript); |
| 26 | + } |
| 27 | + |
| 28 | + [Fact] |
| 29 | + public void HandlesGlobalsWithMultipleProperties() |
| 30 | + { |
| 31 | + // Arrange |
| 32 | + var renderToStringResult = new RenderToStringResult(); |
| 33 | + renderToStringResult.Globals = ToJObject(new |
| 34 | + { |
| 35 | + FirstProperty = "first value", |
| 36 | + SecondProperty = new[] { "Array entry 0", "Array entry 1" } |
| 37 | + }); |
| 38 | + |
| 39 | + // Act |
| 40 | + var actualScript = renderToStringResult.CreateGlobalsAssignmentScript(); |
| 41 | + |
| 42 | + // Assert |
| 43 | + var expectedScript = @"window[""FirstProperty""] = JSON.parse(""\u0022first value\u0022"");" + |
| 44 | + @"window[""SecondProperty""] = JSON.parse(""[\u0022Array entry 0\u0022,\u0022Array entry 1\u0022]"");"; |
| 45 | + Assert.Equal(expectedScript, actualScript); |
| 46 | + } |
| 47 | + |
| 48 | + [Fact] |
| 49 | + public void HandlesGlobalsWithCorrectStringEncoding() |
| 50 | + { |
| 51 | + // Arrange |
| 52 | + var renderToStringResult = new RenderToStringResult(); |
| 53 | + renderToStringResult.Globals = ToJObject(new Dictionary<string, object> |
| 54 | + { |
| 55 | + { "Va<l'u\"e", "</tag>\"'}\u260E" } |
| 56 | + }); |
| 57 | + |
| 58 | + // Act |
| 59 | + var actualScript = renderToStringResult.CreateGlobalsAssignmentScript(); |
| 60 | + |
| 61 | + // Assert |
| 62 | + var expectedScript = @"window[""Va\u003Cl\u0027u\u0022e""] = JSON.parse(""\u0022\u003C\/tag\u003E\\\u0022\u0027}\u260E\u0022"");"; |
| 63 | + Assert.Equal(expectedScript, actualScript); |
| 64 | + } |
| 65 | + |
| 66 | + private static JObject ToJObject(object value) |
| 67 | + { |
| 68 | + return JsonConvert.DeserializeObject<JObject>(JsonConvert.SerializeObject(value)); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments