angular - How to render `<ng-container *ngTemplateOutlet="someTemplate" >` when using testing li

admin2025-04-16  5

We use the testing library and MockBuilder from ng-mocks to write unit tests for angular components:

...
<ng-container *ngTemplateOutlet="previewContent" />
...

<!-- Preview Content -->
<ng-template #previewContent>
  <p data-testid="test-text">template is here :)</p>
</ng-template>

and in the component.spec.ts:

function setupBuilder() {
  return MockBuilder(SomeComponent);
}

async function setup(inputs: {
  // inputs...
}) {
  const builder = setupBuilder();
  const utils = await render(SomeComponent, {
    ...builder.build(),
    inputs,
  });
  const user = userEvent.setup();

  utils.debug();

  return { ...utils, user, component: utils.fixtureponentInstance };
}

describe('SomeComponent', () => {
  it('should render', async () => {
    const { component } = await setup({ ... });
    expect(component).toBeDefined();
    expect(screen.getByTestId('test-text')).toBeInTheDocument();
  });

However, this fails, and the debug logging shows that the template is not included in the rendered DOM.

We use the testing library and MockBuilder from ng-mocks to write unit tests for angular components:

...
<ng-container *ngTemplateOutlet="previewContent" />
...

<!-- Preview Content -->
<ng-template #previewContent>
  <p data-testid="test-text">template is here :)</p>
</ng-template>

and in the component.spec.ts:

function setupBuilder() {
  return MockBuilder(SomeComponent);
}

async function setup(inputs: {
  // inputs...
}) {
  const builder = setupBuilder();
  const utils = await render(SomeComponent, {
    ...builder.build(),
    inputs,
  });
  const user = userEvent.setup();

  utils.debug();

  return { ...utils, user, component: utils.fixture.componentInstance };
}

describe('SomeComponent', () => {
  it('should render', async () => {
    const { component } = await setup({ ... });
    expect(component).toBeDefined();
    expect(screen.getByTestId('test-text')).toBeInTheDocument();
  });

However, this fails, and the debug logging shows that the template is not included in the rendered DOM.

Share Improve this question asked Feb 3 at 13:46 Peter T.Peter T. 3,3255 gold badges37 silver badges45 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

Finally I found the reason and the solution: MockBuilder automatically mocks all things that the component uses, including the NgTemplateOutlet directive... So when I modify my setupBuilder to keep this, it works as expected:

function setupBuilder() {
  return MockBuilder(SomeComponent)
    .keep(NgTemplateOutlet); // <== important if I want the directive to work
}
转载请注明原文地址:http://www.anycun.com/QandA/1744767900a87345.html