Skip to content

Instantly share code, notes, and snippets.

@conficient
Last active March 1, 2022 18:00
Show Gist options
  • Save conficient/1c4dc73592963665a9c05bcaad17cb8f to your computer and use it in GitHub Desktop.
Save conficient/1c4dc73592963665a9c05bcaad17cb8f to your computer and use it in GitHub Desktop.
bUnit Quick Reference
@* need to change project SDK *@
<Project Sdk="Microsoft.NET.Sdk.Razor">
@* add bUnit package *@
<PackageReference Include="bunit" Verion="x.x.x" />
@* Use a `@code` block in a `.razor` test file, e.g. *@
@* if the test component inherits from `TestContext ` you don't need the `new TestContext();` bit
@code {
[Fact]
public void SomeTest()
{
// test counter
using var ctx = new TestContext();
IRenderedFragment cut = ctx.Render(@<Counter />);
// get button and click it
IElement button = cut.Find("button");
button.Click();
IElement paragraph = cut.Find("p");
paragraph.MarkupMatches(@<p>Current count: 1</p>");
// can also call .Change(..), e.g
// from pizza workshop
cut.Find(".toppings-group select").Change("1");
// model is updated:
Assert.NotEmpty(pizza.Toppings);
// markup verifier is relaxed, order and whitespace not important
// when using .MarkupMatches()
// we can ignore content of an element with
<button diff:ignore />
// we can use regex:
<button id:regex="order-\d{3}" .. />
// can find child component
var child = cut.FindComponent<ComponentType>();
// can find child component*S*
var children = cut.FindComponents<ComponentType>();
// check exists:
cut.HasComponent<ComponentType>();
// see _ComponentFactories_ for creating replacements so you can
// ignore child component details
// have same Parameters as original, or have `CaptureUnmatchedValues`
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment