[Test]
public async Task SelectingProduct_GetsIssues()
{
bool fetchCalled = false;
// Set up the route handler before interacting with the page
await Page.RouteAsync("**/issues/forproduct?productid=1", async route =>
{
fetchCalled = true;
await route.ContinueAsync();
});
var selectElement = await Page.QuerySelectorAsync("#ProductId");
Assert.That(selectElement, Is.Not.Null);
var optionValue = "";
await selectElement.SelectOptionAsync(optionValue);
optionValue = "1";
await selectElement.SelectOptionAsync(optionValue);
// Allow some time for the fetch request to be triggered and captured
await Page.WaitForLoadStateAsync(LoadState.NetworkIdle);
Assert.That(fetchCalled, Is.True);
}
The page being tested has a #ProductId select element with a change event handler wired up to it which calls getIssueOptions:
productSelector.addEventListener('change', _ => {
getIssueOptions(issueSelector, Number(productSelector.value));
getEditorialEntries();
});
This test ensures that the getIssueOptions method is fired and that the correct value is passed to the URL of the fetch request that should be made within that method:
const getIssueOptions = (selector:HTMLSelectElement, productId:number) => {
selector.setAttribute('disabled', 'disabled');
if (productId > 0) {
fetch(`/issues/forproduct?productid=${productId}`).then(response => response.json()).then(options => {
const newOptions = [];
newOptions.push(new Option('', ''))
options.forEach(option => {
const d = new Date(option.issueDate);
const text = d.toLocaleDateString('en-GB', { month: 'long', year: 'numeric' });
const o = new Option(text, option.issueId);
newOptions.push(o);
});
selector.replaceChildren(...newOptions);
if(selector.options.length){
selector.removeAttribute('disabled');
}
})
}
}
This tests depends on a Setup similar to that shown in Setup.
Explanation:
Set up the route handler first:
The
RouteAsyncmethod is called beforeSelectOptionAsyncto ensure that the route handler is ready to intercept any requests made as a result of selecting the product.Use the correct route URL:
The route pattern **/issues/forproduct?productId=1 specifically matches the expected fetch request. Adjust it as needed if the query string is dynamic or if you're matching other parts of the URL.
Wait for network activity to finish:
Page.WaitForLoadStateAsync(LoadState.NetworkIdle)is added to ensure that all network activity triggered by the selection has completed. This helps in cases where the request might take some time.Assert after interactions:
The
Assert.That(fetchCalled, Is.True);is placed at the end to confirm that the fetch request was intercepted after the interaction.