Releases: bUnit-dev/bUnit
1.7.7
Added
-
Added method
SetAuthenticationType
toTestAuthorizationContext
to allow for custom authentication type checks. By @TimPurdum. -
Added
DisposeComponents
toTestContextBase
. It will dispose and remove all components rendered by theTestContextBase
. By @linkdotnet. -
Added .NET 7 as a target framework for bUnit. By @linkdotnet.
Fixed
-
Fixed step by step guide for building and viewing the documentation locally. By @linkdotnet.
-
FakeNavigationManager.NavigateTo
could lead to exceptions when navigating to external url's. Reported by (@TDroogers)[https://github.com/TDroogers]. Fixed by @linkdotnet.
1.6.4
A quick minor release that primiarily fixes a regression in 1.5.12.
Fixed
ClickAsync
could lead to bubbling exceptions fromGetDispatchEventTasks
even though they should be handled. Reported by @aguacongas. Fixed by @linkdotnet.- Added more non bubbling events to bUnit so it behaves closer to the HTML specification. @linkdotnet.
1.5.12
This first release of 2022 includes one fix and four additions. A huge thank you to Steven Giesel (@linkdotnet) and Denis Ekart (@denisekart) for their contributions to this release.
Also a big shout out to bUnit's sponsors who helped make this release happen.
The higher tier sponsors are:
Other sponsors are:
- Hassan Rezk Habib (@hassanhabib)
- Jonny Larsson (@Garderoben)
- Domn Werner (@domn1995)
- Mladen Macanović (@stsrki)
- @ChristopheDEBOVE
- Steven Giesel (@linkdotnet)
Added
- Added
FakeSignOutSessionStateManage
type in Blazor, that makes it easy to test components that use theSignOutSessionStateManage
type. By @linkdotnet. - Added a validation to
AddChildContent
method inComponentParameterCollectionBuilder
that will throw an exception if the component'sChildContent
is a generic type. By @denisekart. - Added more optional arguments for
Click
andDoubleClick
extensions which were introduced in .NET 5 and .NET 6. By @linkdotnet. - Added template support for
Nunit
andMSTest
unit test frameworks. By @denisekart.
Fixed
- Changed
GetDispatchEventTasks
for bubbling events such that handled exceptions are not rethrown later from theWaitFor...
helpers methods. Reported by @AndrewStrickland. Fixed by @linkdotnet
1.4.15
This release reintroduces Stub<TComponent>
and related back into the main library, so the "preview" library bunit.web.mock
is already obsolete.
Big shout out to bUnit's sponsors who helped make this release happen.
The higher tier sponsors are:
Other sponsors are:
- Hassan Rezk Habib (@hassanhabib)
- Jonny Larsson (@Garderoben)
- Domn Werner (@domn1995)
- Mladen Macanović (@stsrki)
- @ChristopheDEBOVE
Added
- Add
ComponentFactories
extensions method that makes it easy to register an instance of a replacement component. By @egil. - Add ability to pass
ServiceProviderOptions
toTestServiceProvider
through property to allow users to customize the service provider. By @rodolfograve.
Fixed
- Changed
SetParametersAndRender
such that it rethrows any exceptions thrown by the component under testsSetParametersAsync
method. Thanks to @bonsall for reporting the issue. Fixed by @egil. onclick
on a button inside a form will raise theonsubmit
event for the form itself. Reported by [@egil]. Fixed by @linkdotnet.- Only forms are allowed to have a
onsubmit
event handler. Whenonsubmit
is invoked from a non-form element results in an exception. Fixed by @linkdotnet.
1.3.42
This release includes support for .NET 6, with support for all new features in Blazor with that release. There are also a number of additions and fixes, all listed below.
Big shout out to bUnit's sponsors who helped make this release happen.
The higher tier sponsors are:
Other sponsors are:
- Hassan Rezk Habib (@hassanhabib)
- Jonny Larsson (@Garderoben)
- Domn Werner (@domn1995)
- Mladen Macanović (@stsrki)
- @ChristopheDEBOVE
Added
List of added functionality in this release.
-
Added support for writing tests of components that use the
<FocusOnNavigate>
component included in .NET 6. This includes an assertion helper methodVerifyFocusOnNavigateInvoke
on bUnit'sJSInterop
that allow you to verify that<FocusOnNavigate>
has set focus on an element during render. For example, to verify thath1
selector was used to pick an element to focus on, do:// <App /> component uses <FocusOnNavigate> var cut = RenderComponent<App>(); // Verifies that <FocusOnNavigate> called it's JavaScript function var invocation = JSInterop.VerifyFocusOnNavigateInvoke(); // Verify that the invocation of <FocusOnNavigate> JavaScript function included the "h1" as the selector Assert.Equal("h1", invocation.Arguments[0]);
By @egil.
-
Added fake version of the
PersistentComponentState
type in Blazor that makes it possible to test components that use the type. By @egil. -
Added
TriggerEvent
method to make it easier to trigger custom events. By @egil. -
Added
History
capture in theFakeNavigationManager
. By @egil. -
Added new bUnit component mocking library, available via NuGet as
bunit.web.mock
. It is currently in preview and the features/APIs of it will change! -
Added
WaitForElement
andWaitForElements
methods. These makes it possible to wait for one or more elements to appear in the DOM before continuing a test, similar to howWaitForAssertion
allows you to wait for an assertion to pass, orWaitForState
allows you to wait for a predicate to pass. By @egil.
Changed
- Added automatic conversion of values (types) passed to
Change()
andInput()
event trigger methods. This means that e.g. aDateTime
passed toChange()
is automatically converted to a string format that Blazor expects. By @egil.
Fixed
-
The
Click
andDoubleClick
extension methods now set theMouseEventArgs.Detail
property to1
and2
respectively by default, unless the user specifies something else. This makes the methods more correctly emulate how Blazor reports single or double clicks on an element in the browser. Thanks to @David-Moreira for the help troubleshooting this issue. By @egil. -
FocusAsync()
method handler onElementReference
and<FocusOnNavigate>
js handler return completedTask
. By @anddrzejb. -
Fixes handling of disposed event handlers of bubbling events. See issue #518 for details. Thanks to @David-Moreira for helping debug this issue.
-
Async event trigger methods are not public. In most circumstances you do not need to use them, but if you have a scenario where you want to check that something has not happened after an event handler was triggered, then you can use the async methods and await them to know when they are completed. See #552 for details. By @egil.
1.2.49
Added
List of added functionality in this release.
-
Added more extensions methods to
MarkupMatchesAssertExtensions
to allow asserting withMarkupMatches
onIEnumerable
andIElement
. By @jgoday. -
Added
BunitErrorBoundaryLogger
implementation ofIErrorBoundaryLogger
(needed for Blazor's ErrorBoundary component in .NET 6.0). By @jgoday. -
Added
ComponentFactories
property to theTestContextBase
type. TheComponentFactories
property is aComponentFactoryCollection
type that containsIComponentFactory
types. These are used by bUnits component activator, whenever a component is created during testing. If no component factories is added to the collection, the standard component activator mechanism from Blazor is used. This feature makes it possible to control what components are created normally during a test, and which should be e.g. replaced by a test dummy. More info is available in issue #388.Learn more about this feature on the Controlling component instantiation page.
-
Added
HasComponent<TComponent>()
toIRenderedFragement
. Use it to check if the rendered fragment contains a component of typeTComponent
. Added by @egil. -
Added
AddStub
andAdd
extension methods toComponentFactories
that makes it easy to configure bUnit to replace components in the render tree with stubs. Both methods have overloads that allow for fine grained selection of component types to "double" during testing. Added by @egil in #400.
Changed
List of changes in this release.
-
Updated AngleSharp and related libraries to 0.16.0. NOTE, the new version of AngleSharp includes nullable annotations, which might affect how your code compiles, if you have nullable checking enabled in your test project. By @egil.
-
Updated .NET 6 dependencies to preview 5. By @egil.
Fixed
List of fixes in this release.
-
Fixed JSInterop error message when trying to import an unconfigured module. By @jgoday in #425.
-
Fixed issue where a registered fall-back service provider was not made available to resolve service dependencies of components under test. Thanks to @dady8889 for the reporting the issue.
-
Fixed handling of escaped uri's in FakeNavigationManager. By @linkdotnet in #460.
-
Captured error message from event dispatcher in renderer that would previously be hidden from the user. Related to issue #399.
Release 1.1.5
Added
- All bUnit assemblies is now strong named signed.
- Added .NET 6 (preview 3) as a target framework for bUnit, bUnit.core and bUnit.web.
Changed
- Changed bunit.template such that created projects only reference the bunit package. Bumped other referenced packages to latest version.
1.0.16
[1.0.16] - 2021-04-11
It took a while, but its finally here: a release of bUnit without the preview/beta tag. bUnit has been stable for a long time, so this long overdue, but now at least the wait is over!
The following section list all changes since preview 02.
Changed
List of changes in existing functionality.
-
BREAKING CHANGE: Writing tests using the test components
<Fixture>
and<SnapshotTest>
components inside .razor files has been moved to its own library,bunit.web.testcomponents
. This was done for several reasons:- The feature has been experimental since it was introduced, and it was introduced get a more natural way of specifying the component under test and any related markup used by test.
- The feature is only supported with xUnit.
- There are some issues related to the
SourceFileFinder
library, which is used to discover the test components. - A better way of writing tests in .razor files has been added to bUnit, using "inline render fragments". This method works with all general purpose test frameworks, e.g. MSTest, NUnit, and xUnit, is more flexible, and offer less boilerplate code than the test components. The bUnit documentation has been updated with a guide to this style.
The new package
bunit.web.testcomponents
is provided as is, without expectation of further development or enhancements. If you are using the test components currently for writing tests, it will continue to work for you. If you are starting a new project, or have few of these tests, consider switching to the "inline render fragments" style.Here is a quick comparison of the styles, using a very simple component.
First, the test component style:
@inherits TestComponentBase <Fixture Test="HelloWorldComponentRendersCorrectly"> <ComponentUnderTest> <HelloWorld /> </ComponentUnderTest> @code { void HelloWorldComponentRendersCorrectly(Fixture fixture) { // Act var cut = fixture.GetComponentUnderTest<HelloWorld>(); // Assert cut.MarkupMatches("<h1>Hello world from Blazor</h1>"); } } </Fixture> <SnapshotTest Description="HelloWorld component renders correctly"> <TestInput> <HelloWorld /> </TestInput> <ExpectedOutput> <h1>Hello world from Blazor</h1> </ExpectedOutput> </SnapshotTest>
The a single test in "inline render fragments" style covers both cases:
@inherits TestContext @code { [Fact] public void HelloWorldComponentRendersCorrectly() { // Act var cut = Render(@<HelloWorld />); // Assert cut.MarkupMatches(@<h1>Hello world from Blazor</h1>); } }
To make the snapshot test scenario even more compact, consider putting all code in one line, e.g.
Render(@<HelloWorld />).MarkupMatches(@<h1>Hello world from Blazor</h1>);
.For a more complete snapshot testing experience, I recommend looking at Simon Cropp's Verify library, in particular the Verify.Blazor extension to bUnit. Verify comes with all the features you expect from a snapshot testing library.
Removed
List of now removed features.
-
The
AddXunitLogger
method, which provided support for capturingILogger
messages and passing them to xUnit'sITestOutputHelper
, has been removed. There were no need to keep xUnit specific code around in bUnit going forward, and there are many implementations on-line that supports this feature, so having it in bUnit made little sense. One such alternative, which bUnit has adopted internally, is to use Serilog. This looks as follows:- Add the following packages to your test project:
Serilog
,Serilog.Extensions.Logging
, andSerilog.Sinks.XUnit
. - Add the following class/extension method to your test project (which replicates the signature of the removed
AddXunitLogger
method):
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Serilog; using Serilog.Events; using Xunit.Abstractions; namespace Bunit { public static class ServiceCollectionLoggingExtensions { public static IServiceCollection AddXunitLogger(this IServiceCollection services, ITestOutputHelper outputHelper) { var serilogLogger = new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.TestOutput(outputHelper, LogEventLevel.Verbose) .CreateLogger(); services.AddSingleton<ILoggerFactory>(new LoggerFactory().AddSerilog(serilogLogger, dispose: true)); services.AddSingleton(typeof(ILogger<>), typeof(Logger<>)); return services; } } }
- Add the following packages to your test project:
-
The
bunit.xunit
package has been removed, since it is no longer needed (there is no code left in it).
1.0.0 - preview 02 - final release before v1
[1.0.0-preview-02] - 2021-03-26
The following sections list all changes in 1.0.0 preview 02.
The plan is to make this the last preview release of bUnit. If no big blocking bugs show up the next two weeks, a non-preview release of bUnit will be pushed out to the world.
Added
List of new features.
-
Added the ability to pass a "fallback
IServiceProvider
" to theTestServiceProvider
, available through theServices
property on aTestContext
. The fallback service provider enables a few interesting scenarios, such as using an alternative IoC container, or automatically generating mocks of services components under test depend on. See the Injecting Services into Components Under Test page for more details on this feature. By @thopdev in #310. -
Added
Task<Expection> ITestRenderer.UnhandledException
property that returns aTask<Exception>
that completes when the renderer captures an unhandled exception from a component under test. If a component is missing exception handling of asynchronous operations, e.g. in theOnInitializedAsync
method, the exception will not break the test, because it happens on another thread. To have a test fail in this scenario, you can await theUnhandledException
property on theTestContext.Renderer
property, e.g.:using var ctx = new TestContext(); var cut = ctx.RenderComponent<ComponentThatThrowsDuringAsyncOperation>(); Task<Exception?> waitTimeout = Task.Delay(500).ContinueWith(_ => Task.FromResult<Exception?>(null)).Unwrap(); Exception? unhandledException = await Task.WhenAny<Exception?>(Renderer.UnhandledException, waitTimeout).Unwrap(); Assert.Null(unhandledException);
In this example, we await any unhandled exceptions from the renderer, or our wait timeout. The
waitTimeout
ensures that we will not wait forever, in case no unhandled exception is thrown.NOTE, a better approach is to use the
WaitForState
orWaitForAssertion
methods, which now also throws unhandled exceptions. Using them, you do not need to set up a wait timeout explicitly. -
Added a simple fake navigation manager, which is registered by default in bUnit's service provider. When the fake navigation manager's
NavigateTo
method is called, it does two things:- Set the
Uri
property to the URI passed to theNavigateTo
method (with the URI normalized to an absolute URI). - Raise the
LocationChanged
event with the URI passed to theNavigateTo
method.
Lets look at an example: To verify that the
<GoesToFooOnInit>
component below calls theNavigationManager.NavigateTo
method with the expected value, do the following:<GoesToFooOnInit>
component:@inject NavigationManager NavMan @code { protected override void OnInitialized() { NavMan.NavigateTo("foo"); } }
Test code:
// Arrange using var ctx = new TestContext(); var navMan = ctx.Services.GetRequiredService<NavigationManager>(); // Act var cut = ctx.RenderComponent<GoesToFooOnInit>(); // Assert Assert.Equal($"{navMan.BaseUri}foo", navMan.Uri);
Since the
foo
input argument is normalized to an absolute URI, we have to do the same normalization in our assertion.The fake navigation manager's
BaseUri
is set tohttp://localhost/
, but it is not recommended to use that URL directly in your code. Instead create an assertion by getting that value from theBaseUri
property, like shown in the example above. - Set the
-
Added additional bUnit JSInterop
Setup
methods, that makes it possible to get complete control of invocation matching for the created handler. By @egil.
Changed
List of changes in existing functionality.
-
WaitForAssertion
andWaitForState
now throws unhandled exception caught by the renderer from a component under test. This can happen if a component is awaiting an asynchronous operation that throws, e.g. a API call using a misconfiguredHttpClient
. By @egil in #310. -
Improvements to error message from bUnit's JSInterop when it receives an invocation that it has not been set up to handle. By @egil in #346.
1.0.0 - preview 01
[1.0.0-preview-01] - 2020-12-24
Happy holidays everyone. This release marks the first preview release of bUnit, which means that only small features additions and bugfixes will follow before version 1.0.0 is release soon.
Yet again many folks in the community have contributes by raising issues, answering questions, sending in pull requests and taking part in design discussions. A huge thanks to all of you. Also, a huge thanks to the sponsors of the project.
The following section list all changes in 1.0.0 preview 01.
Added
List of new features.
-
Added support for casting
BUnitJSRuntime
toIJSInProcessRuntime
andIJSUnmarshalledRuntime
. By @KristofferStrube in #279 -
Added support for triggering
@ontoggle
event handlers through a dedicatedToggle()
method. By @egil in #256. -
Added out of the box support for
<Virtualize>
component. When a<Virtualize>
component is used in a component under test, it's JavaScript interop-calls are faked by bUnits JSInterop, and it should result in all items being rendered immediately. By @egil in #240. -
Added support for components that call
ElementReference.FocusAsync
. These calls are handled by the bUnits JSInterop, that also allows you to verify thatFocusAsync
has been called for a specific element. For example, if a component has rendered an<input>
element, then the following code will verify that it has been focused usingFocusAsync
:var cut = RenderComponent<FocusingComponent>(); var input = cut.Find("input"); JSInterop.VerifyFocusAsyncInvoke() .Arguments[0] // the first argument is the ElemenetReference .ShouldBeElementReferenceTo(input);
-
Added
Render(RenderFragment)
andRender<TComponent>(RenderFragment)
methods toTestContext
, as well as various overloads to theMarkupMatches
methods, that also takes aRenderFragment
as the expected value.The difference between the generic
Render
method and the non-generic one is that the generic returns anIRenderedComponent<TComponent>
, whereas the non-generic one returns aIRenderedFragment
.Calling
Render<TComponent>(RenderFragent)
is equivalent to callingRender(RenderFragment).FindComponent<TComponent>()
, e.g. it returns the first component in the render tree of typeTComponent
. This is different from theRenderComponent<TComponent>()
method, whereTComponent
is the root component of the render tree.The main usecase for these are when writing tests inside .razor files. Here the inline syntax for declaring render fragments make these methods very useful.
For example, to tests the
<Counter>
page/component that is part of new Blazor apps, do the following (inside aCounterTest.razor
file):@code { [Fact] public void Counter_Increments_When_Button_Is_Clicked() { using var ctx = new TestContext(); var cut = ctx.Render(@<Counter />); cut.Find("button").Click(); cut.Find("p").MarkupMatches(@<p>Current count: 1</p>); } }
Note: This example uses xUnit, but NUnit or MSTest works equally well.
In addition to the new
Render
methods, a emptyBuildRenderTree
method has been added to theTestContext
type. This makes it possible to inherit from theTestContext
type in test components, removing the need for newing up theTestContext
in each test.This means the test component above ends up looking like this:
@inherts TestContext @code { [Fact] public void Counter_Increments_When_Button_Is_Clicked() { var cut = Render(@<Counter />); cut.Find("button").Click(); cut.Find("p").MarkupMatches(@<p>Current count: 1</p>); } }
Tip: If you have multiple test components in the same folder, you can add a
_Imports.razor
file inside it and add the@inherits TestContext
statement in that, removing the need to add it to every test component. -
Added support for
IJSRuntime.InvokeAsync<IJSObjectReference>(...)
calls from components. There is now a new setup helper methods for configuring how invocations towards JS modules should be handled. This is done with the variousSetupModule
methods available on theBunitJSInterop
type available through theTestContext.JSInterop
property. For example, to set up a module for handling calls tofoo.js
, do the following:using var ctx = new TestContext(); var moduleJsInterop = ctx.JSInterop.SetupModule("foo.js");
The returned
moduleJsInterop
is aBunitJSInterop
type, which means all the normalSetup<TResult>
andSetupVoid
methods can be used to configure it to handle calls to the module from a component. For example, to configure a handler for a call tohello
in thefoo.js
module, do the following:moduleJsInterop.SetupVoid("hello");
-
Added support for registering services in bUnits
Services
collection that implementsIAsyncDisposable
. Suggested by @jmaillet in #249.
Changed
List of changes in existing functionality.
-
bUnit's mock IJSRuntime has been moved to an "always on" state by default, in strict mode, and is now available through
TestContext
'sJSInterop
property. This makes it possible for first party Blazor components like the<Virtualize>
component, which depend on JSInterop, to "just work" in tests.Compatible with previous releases: To get the same effect as calling
Services.AddMockJSRuntime()
in beta-11, which used to add the mock IJSRuntime in "loose" mode, you now just need to change the mode of the already on JSInterop, i.e.ctx.JSInterop.Mode = JSRuntimeMode.Loose
.Inspect registered handlers: Since the new design allows registering invoke handlers in the context of the
TestContext
, you might need to get already registered handlers in your individual tests. This can be done with theTryGetInvokeHandler()
method, that will return handler that can handle the parameters passed to it. E.g. to get a handler for aIJSRuntime.InvokaAsync<string>("getValue")
, callctx.JSInterop.TryGetInvokeHandler<string>("getValue")
.Learn more issue #237. By @egil in #247.
-
The
Setup<TResult>(string identifier, Func<IReadOnlyList<object?>, bool> argumentsMatcher)
andSetupVoid(string identifier, Func<IReadOnlyList<object?>, bool> argumentsMatcher)
methods in bUnits JSInterop/MockJSRuntime has a new second parameter, anInvocationMatcher
.The
InvocationMatcher
type is a delegate that receives aJSRuntimeInvoation
and returns true. TheJSRuntimeInvoation
type contains the arguments of the invocation and the identifier for the invocation. This means old code using theSetup
andSetupVoid
methods should be updated to use the arguments list inJSRuntimeInvoation
, e.g., change the following call:ctx.JSInterop.Setup<string>("foo", args => args.Count == 2)
to this:
ctx.JSInterop.Setup<string>("foo", invocation => invocation.Arguments.Count == 2)
. -
Changed
AddTestAuthorization
such that it works in Razor-based test contexts, i.e. on theFixture
andSnapshotTest
types.
Removed
List of now removed features.
- A few bUnit internal xUnit assert helper methods, the custom
ShouldAllBe
methods, has mistakingly been part of the bunit.xunit package. These have been removed.
Fixed
List of any bug fixes.
-
When an
Add
call to the component parameter collection builder was used to select a parameter that was inherited from a base component, the builder incorrectly reported the selected property/parameter as missing on the type. Reported by @nickmuller in #250. -
When an element, found in the DOM tree using the
Find()
, method was removed because of an event handler trigger on it, e.g. ancut.Find("button").Click()
event trigger method, anElementNotFoundException
was thrown. Reported by @nickmuller in #251. -
In the built-in fake authentication system in bUnit, roles and claims were not available in components through the a cascading parameter of type
Task<AuthenticationState>
. Reported by @AFAde in #253 and fixed in #291 by @egil.