Skip to content

Looking for how to create unit test with c# when the component creates a canvas (BECanvasComponent) #52

@sakvin1

Description

@sakvin1

Hi,
I encounter an issue when I tried to create a unit test for a component that creating a canvas. Unit Test failed with this message.

Message:
Test method TestCanvas threw exception:
System.AggregateException: One or more errors occurred. (Object reference not set to an instance of an object.) ---> System.NullReferenceException: Object reference not set to an instance of an object.
IndexComponent.OnAfterRenderAsync(Boolean firstRender) line 24

This is the line that causes an error in Index.razor.cs.

24.     Console.WriteLine("width={0}.", m.Width.ToString());

Basically, I can't create a JS mock for Blazor.Extensions.Canvas.Canvas2D. Following are the code.

In Index.razor

@page "/Index"
@inherits IndexComponent
<BECanvas Width="800" Height="800" @ref="_canvasReference"></BECanvas>

In Index.razor.cs

using Blazor.Extensions.Canvas.Canvas2D;
using Blazor.Extensions;
public class IndexComponent : ComponentBase
{
    protected BECanvasComponent _canvasReference;
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
       Canvas2DContext context = await _canvasReference.CreateCanvas2DAsync();
       var m = await context.MeasureTextAsync("Hello Blazor");
       Console.WriteLine("width={0}.", m.Width.ToString());  // Line 24 that causes the error which m returns null in this case.
    }
}

In Test.cs

[TestMethod]
public async Task TestCanvas()
{
    var jsMock = Services.AddMockJsRuntime(JsRuntimeMockMode.Loose);
    var cut = RenderComponent<Index>();
}

Please help.

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions