Please see this simplified Blazor component MyComponent
:
<button id="enableButton" @onclick="Enable">Enable</button>
<button id="disableButton" @onclick="Disable">Disable</button>
<select disabled="@_disabled">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
@code {
private bool _disabled;
private void Enable() { _disabled = false; }
private void Disable() { _disabled = true; }
}
And here are two simple bUnit tests for the Blazor component:
[Test]
public void Enable()
{
using var testContext = new TestContext();
var testee = testContext.RenderComponent<MyComponent>();
testee.Find("[id^=\"enableButton\"]").Click();
testee.Find("select").IsDisabled().Should().BeFalse();
}
[Test]
public void Disable()
{
using var testContext = new TestContext();
var testee = testContext.RenderComponent<MyComponent>();
testee.Find("[id^=\"disableButton\"]").Click();
testee.Find("select").IsDisabled().Should().BeTrue();
}
The Disable
test fails with Expected testee.Find("select").IsDisabled() to be true, but found False.
. But when rendering MyComponent
in the browser, everything works as expected.
What am I doing wrong?
CodePudding user response:
Blazor renders all boolean attributes that are truthy without a value, and when a boolean attribute is assigned false, it is simply not rendered. That is perfectly legal from a HTML5 spec point of view, but non-the-less surprising.
This means that when your _disabled
is false
, the disabled
attribute does not exist in the rendered markup. To verify this, you can do:
testee.Find("select").HasAttribute("disabled").Should().BeFalse()
When _disabled
is true
, you can verify this with:
testee.Find("select").HasAttribute("disabled").Should().BeTrue();