最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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.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.

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
}
发布评论

评论列表(0)

  1. 暂无评论