Using ng-mocks, how do I render a template that is not wrapped by any directive or component?

251 views Asked by At

I'm trying to test a simple Angular component scenario. I have a component, and in it there's a template that renders some content. This template can later be used for anything.

I would like to write a test that verifies the content of this template. I'm using ng-mocks. The ng-mocks documentation has a lot of examples of how to deal with templates that wrapped by components or provided by directives. But it doesn't tell you how to do this if the template is "parentless", sitting in the component view on its own, without any directives or wrapping components.

This is an example of my component template

<ng-template #tpl>{{ whatever }} </ng-template>

I would like to use ng-mocks to find a reference to this template and then render it. I can't find a way to do this since ng-mocks' render function requires a mocked component instance as the first parameter.

I set up this stackblitz to demonstrate what I'm trying to achieve. What am I missing?

Thanks!

2

There are 2 answers

0
satanTime On

That's a good question, but ng-mocks doesn't work this way.

To render a template, ng-mocks needs to have access to its ViewContainerRef. Usually, components or directives have a ref to the template. And if the component or the directive has been mocked, then ng-mocks has this ref too and can create ViewContainerRef during the build process and render and hide templates.

There are 2 issues in your example:

  • there is no ref between TargetComponent and tpl
  • ref should belong to a mock component / directive

But, because your component is responsible for rendering and it's not mocked, the render should be done via the component's interface.

0
5te1n On

I have the same problem. To solve it, I did the following:

    const templateRef = ngMocks.findTemplateRef( 'tpl' );

    const viewContainerRef = ngMocks.get( fixture.point, ViewContainerRef );
    viewContainerRef.createEmbeddedView( templateRef );

This way the template is rendered next to the component that you are testing.