Testing components under HeadContent #593
-
I tried to create a test which checks whether or not some specific Component.razor: <HeadContent>
<meta name="title" property="og:title" content="@Title" />
</HeadContent>
@code {
[Parameter]
public string Title { get; set; }
} Test: [Fact]
public void ShouldRenderMetaTagsWhenSet()
{
var cut = RenderComponent<Component>(p => p .Add(s => s.Title, "Title"));
var metaTags = cut.FindAll("meta");
var titleMeta = metaTags.SingleOrDefault(m => m.Attributes.Any(a => a.Name == "title"));
titleMeta.Should().NotBeNull();
titleMeta.NodeValue.Should().Be("Title");
} Now the tests fails and the markup for the component is empty. The reason is that the Now out of my head there are two questions:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hi Steven, With the introduction of component factories, this is probably the best solution for solving this. The simpel approach that is supported right now is something like this: ComponentFactories.AddStub<HeadContent>();
var cut = RenderComponent<Component>(p => p .Add(s => s.Title, "Title"));
var headContent = cut.FindComponent<Stub<HeadContent>>();
var headContentChildContent = Render(headContent.Instance.Parameters.Get(p => p.ChildContent));
var metaTags = headContentChildContent.FindAll("meta");
var titleMeta = metaTags.SingleOrDefault(m => m.Attributes.Any(a => a.Name == "title"));
titleMeta.Should().NotBeNull();
titleMeta.NodeValue.Should().Be("Title"); Obviously that is very verbose. Less verbose is this approach, where you tell the stub to render something out instead of the original component. In this case, we are telling it to get whatever child content was passed to the HeadContent component and just add it directly in place of the HeadContent.: ComponentFactories.AddStub<HeadContent>(ps => ps.Get(p => p.ChildContent));
var cut = RenderComponent<Component>(p => p .Add(s => s.Title, "Title"));
var metaTags = cut.FindAll("meta");
var titleMeta = metaTags.SingleOrDefault(m => m.Attributes.Any(a => a.Name == "title"));
titleMeta.Should().NotBeNull();
titleMeta.NodeValue.Should().Be("Title"); |
Beta Was this translation helpful? Give feedback.
Hi Steven,
With the introduction of component factories, this is probably the best solution for solving this. The simpel approach that is supported right now is something like this:
Obviously that is very v…