Skip to content

Commit

Permalink
Refactor JsInteropCookieService
Browse files Browse the repository at this point in the history
  • Loading branch information
YuriyDurov committed Dec 4, 2024
1 parent 8eb6d70 commit 4275b6f
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 7 deletions.
13 changes: 7 additions & 6 deletions src/BitzArt.Blazor.Cookies/Services/JsInteropCookieService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,13 @@ public async Task<IEnumerable<Cookie>> GetAllAsync()
var raw = await js.InvokeAsync<string>("eval", "document.cookie");
if (string.IsNullOrWhiteSpace(raw)) return [];

return raw.Split("; ").Select(x =>
{
var parts = x.Split("=", 2);
if (parts.Length != 2) throw new Exception($"Invalid cookie format: '{x}'.");
return new Cookie(parts[0], parts[1]);
});
return raw.Split("; ").Select(GetCookie);
}

private Cookie GetCookie(string raw)
{
var parts = raw.Split("=", 2);
return new Cookie(parts[0], parts[1]);
}

public async Task<Cookie?> GetAsync(string key)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\src\BitzArt.Blazor.Cookies\BitzArt.Blazor.Cookies.csproj" />
<ProjectReference Include="..\..\src\BitzArt.Blazor.Cookies\BitzArt.Blazor.Cookies.csproj" />
</ItemGroup>

<ItemGroup>
Expand Down
47 changes: 47 additions & 0 deletions tests/BitzArt.Blazor.Cookies.Tests/JsInteropCookieServiceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using Microsoft.JSInterop;
using Moq;

namespace BitzArt.Blazor.Cookies.Tests;

public class JsInteropCookieServiceTests
{
[Fact]
public async Task GetAsync_WithCookieNotPresent_ShouldReturnNull()
{
// Arrange
var jsRuntime = new Mock<IJSRuntime>();
jsRuntime.Setup(x => x.InvokeAsync<string>("eval", It.IsAny<object[]>()))
.ReturnsAsync("");

var sut = new JsInteropCookieService(jsRuntime.Object);

// Act
var result = await sut.GetAsync("my-cookie");

// Assert
Assert.Null(result);
}

[Theory]
[InlineData("my-cookie", "")]
[InlineData("my-cookie", "my-value")]
[InlineData("my-cookie", "value=123")]
[InlineData("my-cookie", "value_a=a value_b=b")]
[InlineData("my-cookie", "!@#$%^&*()-_=_-)(*&^%$#@!")]
[InlineData("my-cookie", "abc !@#$%^&*()-_ = _-)(*&^%$#@! def 123456789 ghi")]
public async Task GetAsync_WithCookiePresent_ShouldReturnValue(string cookieName, string cookieValue)
{
// Arrange
var jsRuntime = new Mock<IJSRuntime>();
jsRuntime.Setup(x => x.InvokeAsync<string>("eval", It.IsAny<object[]>()))
.ReturnsAsync($"{cookieName}={cookieValue}; path=/");

var sut = new JsInteropCookieService(jsRuntime.Object);

// Act
var result = await sut.GetAsync(cookieName);

// Assert
Assert.Equal(cookieValue, result?.Value);
}
}

0 comments on commit 4275b6f

Please sign in to comment.