Skip to content

Commit

Permalink
test: FHB-113 unit tests (#249)
Browse files Browse the repository at this point in the history
* test: WhenLanguageOnGetIsCalled

* test: WhenWhatLanguageOnPostIsCalled.cs

* test: post add test

Also added more descriptive method names
  • Loading branch information
StuwiiDev authored Nov 22, 2024
1 parent ea46481 commit 0907cec
Show file tree
Hide file tree
Showing 4 changed files with 202 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using System.Text.Json;
using FamilyHubs.ServiceDirectory.Admin.Core.DistributedCache;
using FamilyHubs.ServiceDirectory.Admin.Core.Models.ServiceJourney;
using FamilyHubs.ServiceDirectory.Admin.Web.Pages.manage_services;
using Microsoft.AspNetCore.Mvc.Rendering;
using NSubstitute;
using Xunit;

namespace FamilyHubs.ServiceDirectory.Admin.Web.UnitTests.Pages.manage_services;

public class WhenWhatLanguageOnGetIsCalled
{
private readonly IRequestDistributedCache _mockCache;

public WhenWhatLanguageOnGetIsCalled()
{
_mockCache = Substitute.For<IRequestDistributedCache>();
}

[Fact]
public async Task OnGetWithModel_NoUserInputOrPreviousEntry_PopulatesUserLanguageOptionsWithDefault()
{
// Arrange
var cachedData = new ServiceModel<WhatLanguageViewModel>();
_mockCache.GetAsync<ServiceModel<WhatLanguageViewModel>>(Arg.Any<string>()).Returns(cachedData);

var model = new What_LanguageModel(_mockCache);

// Act
await model.OnGetAsync("add", null, false);

// Assert
var expectedOptions = new List<SelectListItem>
{
new("", ""),
};

Assert.Equal(expectedOptions.Select(o => o.Value), model.UserLanguageOptions.Select(o => o.Value));
Assert.Equal(expectedOptions.Select(o => o.Text), model.UserLanguageOptions.Select(o => o.Text));
}

[Fact]
public async Task OnGetWithModel_NoUserInputWithPreviousEntry_PopulatesUserLanguageOptionsFromServiceModel()
{
// Arrange
var cachedData = new ServiceModel<WhatLanguageViewModel>
{
LanguageCodes = new List<string> { "en", "fr" }
};
_mockCache.GetAsync<ServiceModel<WhatLanguageViewModel>>(Arg.Any<string>()).Returns(cachedData);

var model = new What_LanguageModel(_mockCache);

// Act
await model.OnGetAsync("add", null, false);

// Assert
var expectedOptions = new List<SelectListItem>
{
new("English", "en"),
new("French", "fr")
};

Assert.Equal(expectedOptions.Select(o => o.Value), model.UserLanguageOptions.Select(o => o.Value));
Assert.Equal(expectedOptions.Select(o => o.Text), model.UserLanguageOptions.Select(o => o.Text));
}

[Fact]
public async Task OnGetWithModel_RedirectingToSelf_PopulatesUserLanguageOptionsFromUserInput()
{
// Arrange
var mockVm = new WhatLanguageViewModel
{
Languages = ["English", "French"]
};
var cachedData = new ServiceModel<WhatLanguageViewModel>
{
UserInput = mockVm,
UserInputType = typeof(WhatLanguageViewModel).FullName,
UserInputJson = JsonSerializer.Serialize(mockVm),
LanguageCodes = new List<string> { "de" } // <- Here to prove it only gets values from UserInput
};
_mockCache.GetAsync<ServiceModel<WhatLanguageViewModel>>(Arg.Any<string>()).Returns(cachedData);

var model = new What_LanguageModel(_mockCache);

// Act
await model.OnGetAsync("add", null, true);

// Assert
var expectedOptions = new List<SelectListItem>
{
new("English", "en"),
new("French", "fr")
};

Assert.Equal(expectedOptions.Select(o => o.Value), model.UserLanguageOptions.Select(o => o.Value));
Assert.Equal(expectedOptions.Select(o => o.Text), model.UserLanguageOptions.Select(o => o.Text));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
using System.Text.Json;
using FamilyHubs.ServiceDirectory.Admin.Core.DistributedCache;
using FamilyHubs.ServiceDirectory.Admin.Core.Models.ServiceJourney;
using FamilyHubs.ServiceDirectory.Admin.Web.Pages.manage_services;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
using NSubstitute;
using Xunit;

namespace FamilyHubs.ServiceDirectory.Admin.Web.UnitTests.Pages.manage_services;

public class WhenWhatLanguageOnPostIsCalled
{
private readonly IRequestDistributedCache _mockCache;

public WhenWhatLanguageOnPostIsCalled()
{
_mockCache = Substitute.For<IRequestDistributedCache>();
}

[Fact]
public async Task OnPostWithModel_RemoveButton_RemovesLanguage()
{
// Arrange
var cachedData = new ServiceModel<WhatLanguageViewModel>();
var model = new What_LanguageModel(_mockCache)
{
ServiceModel = cachedData
};
_mockCache.GetAsync<ServiceModel<WhatLanguageViewModel>>(Arg.Any<string>()).Returns(cachedData);

var formCollection = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>
{
{ "button", "remove-1" }, // Simulate remove button click for the second language
{ "language", new Microsoft.Extensions.Primitives.StringValues(["en", "fr", "de"]) }
});

var httpContext = new DefaultHttpContext
{
Request = { Form = formCollection }
};

model.PageContext.HttpContext = httpContext;

// Act
await model.OnPostAsync("add", null, default);

// Assert
// Necessary deserialization of UserInputJson as the model does not retain the UserInput
var userInput = JsonSerializer.Deserialize<WhatLanguageViewModel>(model.ServiceModel.UserInputJson!);
var updatedLanguages = userInput!.Languages.ToList();
Assert.NotNull(updatedLanguages);
Assert.DoesNotContain("fr", updatedLanguages);
Assert.Equal(2, updatedLanguages!.Count);
}

[Fact]
public async Task OnPostWithModel_AddButton_AddsLanguage()
{
// Arrange
var cachedData = new ServiceModel<WhatLanguageViewModel>();
var model = new What_LanguageModel(_mockCache)
{
ServiceModel = cachedData
};
_mockCache.GetAsync<ServiceModel<WhatLanguageViewModel>>(Arg.Any<string>()).Returns(cachedData);

var formCollection = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues>
{
{ "button", "add" }, // Simulate add button click
{ "language", new Microsoft.Extensions.Primitives.StringValues(["en", "fr", "de"]) }
});

var httpContext = new DefaultHttpContext
{
Request = { Form = formCollection }
};

model.PageContext.HttpContext = httpContext;

// Act
await model.OnPostAsync("add");

// Assert
// Necessary deserialization of UserInputJson as the model does not retain the UserInput
var userInput = JsonSerializer.Deserialize<WhatLanguageViewModel>(model.ServiceModel.UserInputJson!);
var updatedLanguages = userInput!.Languages.ToList();
Assert.NotNull(updatedLanguages);
Assert.Contains("English", updatedLanguages);
Assert.Contains("French", updatedLanguages);
Assert.Contains("German", updatedLanguages);
Assert.Contains("", updatedLanguages); // <- Adds the new field
Assert.Equal(4, updatedLanguages!.Count);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using System.Diagnostics;
using System.Text.Json;
using System.Text.Json;

namespace FamilyHubs.ServiceDirectory.Admin.Core.Models;

Expand All @@ -22,8 +21,6 @@ public void AddErrorState(TJourneyPage page, TErrorId[] errors)

public void PopulateUserInput()
{
Debug.Assert(UserInput == null);

if (UserInputType != null && UserInputJson != null
&& UserInputType == typeof(TUserInput).FullName)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public What_LanguageModel(IRequestDistributedCache connectionRequestCache)

protected override void OnGetWithError()
{
SetFormUserInputData();
SetFormDataFromUserInput();

if (ServiceModel?.UserInput?.ErrorIndexes == null)
{
Expand All @@ -71,13 +71,13 @@ protected override void OnGetWithError()
protected override void OnGetWithModel()
{
// redirectingToSelf is only set when adding a new field. Javascript is disabled
if(ServiceModel?.UserInput is not null && Request.Query.TryGetValue("redirectingToSelf", out var redirectToSelf) && redirectToSelf == "true")
if(ServiceModel?.UserInput is not null && RedirectingToSelf)
{
SetFormUserInputData();
SetFormDataFromUserInput();
return;
}

SetFormServiceModelData();
SetFormDataFromServiceModel();
}

protected override IActionResult OnPostWithModel()
Expand Down Expand Up @@ -168,7 +168,7 @@ private static IEnumerable<string> RemoveLanguageAtIndex(int index, IEnumerable<
return updatedList;
}

private void SetFormServiceModelData()
private void SetFormDataFromServiceModel()
{
SetServiceModelLanguageOptions();

Expand All @@ -177,7 +177,7 @@ private void SetFormServiceModelData()

}

private void SetFormUserInputData()
private void SetFormDataFromUserInput()
{
// Override with the languages that are already selected
SetUserInputLanguageOptions();
Expand All @@ -194,7 +194,6 @@ private void SetServiceModelLanguageOptions()
{
UserLanguageOptions = ServiceModel!.LanguageCodes.Select(lang =>
{
//todo: put into method
var codeFound = Languages.CodeToName.TryGetValue(lang, out var name);
return new SelectListItem(name, codeFound ? lang : InvalidNameValue);
});
Expand Down

0 comments on commit 0907cec

Please sign in to comment.