Skip to content

How to test components with ng-content? #78

@tonivj5

Description

@tonivj5

Hey, I'm testing components that rely completely in <ng-content>.

Here is a component I want to test:

import { Component, ChangeDetectionStrategy, Inject } from '@angular/core';

import { use } from '@core/utils';

import { CONTEXT } from '../table/tokens';

@Component({
  template: `
    <p data-testid="too-long-cell" [style.width]="context">
      <ng-content></ng-content>
    </p>
  `,
  styles: [
    `
      p {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TooLongCellComponent {
  constructor(@Inject(CONTEXT) public context = '150px') {}
}

And I have written this test:

import { Component, ChangeDetectionStrategy } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { render } from '@testing-library/angular';

import { CONTEXT } from '../table/tokens';
import { TooLongCellComponent } from './too-long-cell.component';

export function getTestingComponent(template: string) {
  @Component({
    template,
    changeDetection: ChangeDetectionStrategy.OnPush,
  })
  class TestComponent {}

  return TestComponent;
}

function createComponent({ width }: { width?: number } = {}) {
  TestBed.overrideComponent(TooLongCellComponent, { set: { selector: 'cell' } });

  return render(getTestingComponent('<cell>projected value</cell>'), {
    providers: [
      {
        provide: CONTEXT,
        useValue: width,
      },
    ],
    declarations: [TooLongCellComponent],
  });
}

describe(TooLongCellComponent, () => {
 it('should add a width property with 100px', async () => {
    const { getByTestId } = await createComponent({ width: '100px' });

    const cell = getByTestId('too-long-cell');

    expect(cell.style.width).toBe('100px');
    expect(cell).toHaveTextContent(/^projected value$/);
  });
});

Could we improve the testing of <ng-content> using angular-testing-library? Or should I do in this way?

Thanks 👍

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions