npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

shallow-render

v18.0.0

Published

Shallow rendering test utility for Angular

Downloads

23,853

Readme

shallow-render

CircleCI npm version

Angular testing made easy with shallow rendering and easy mocking.


Docs

Schematics

Articles

Angular Version Support

| Angular | shallow-render | |---------|----------------| | 18x | 18x | | 17x | 17x | | 16x | 16x | | 15x | 15x | | 14x | 14x | | 13x | 13x | | 12x | 12x | | 11x | 11x | | 10x | 10x | | 9x | 9x | | 6x-8x | 8x | | 5x | <= 7.2.0 |

Super Simple Tests

describe('ColorLinkComponent', () => {
  let shallow: Shallow<ColorLinkComponent>;

  beforeEach(() => {
    shallow = new Shallow(ColorLinkComponent, MyModule);
  });

  it('renders a link with the name of the color', async () => {
    const { find } = await shallow.render({ bind: { color: 'Blue' } });
    // or shallow.render(`<color-link color="Blue"></color-link>`);

    expect(find('a').nativeElement.textContent).toBe('Blue');
  });

  it('emits color when clicked', async () => {
    const { element, outputs } = await shallow.render({ bind: { color: 'Red' } });
    element.click();

    expect(outputs.handleClick.emit).toHaveBeenCalledWith('Red');
  });
});

The problem

Testing in Angular is HARD. TestBed is powerful but its use in component specs ends with lots of duplication.

Here's a standard TestBed spec for a component that uses a few other components, a directive and a pipe and handles click events:

describe('MyComponent', () => {
  beforeEach(async => {
    return TestBed.configureTestModule({
      imports: [SomeModuleWithDependencies],
      declarations: [
        TestHostComponent,
        MyComponent, // <-- All I want to do is test this!!
        // We either must list all our dependencies here
        // -- OR --
        // Use NO_ERRORS_SCHEMA which allows any HTML to be used
        // even if it is invalid!
        ButtonComponent,
        LinkComponent,
        FooDirective,
        BarPipe,
      ],
      providers: [MyService],
    })
      .compileComponents()
      .then(() => {
        let myService = TestBed.get(MyService); // Not type safe
        spyOn(myService, 'foo').and.returnValue('mocked foo');
      });
  });

  it('renders a link with the provided label text', () => {
    const fixture = TestBed.createComponent(TestHostComponent);
    fixture.componentInstance.labelText = 'my text';
    fixture.detectChanges();
    const link = fixture.debugElement.query(By.css('a'));

    expect(a.nativeElement.textContent).toBe('my text');
  });

  it('sends "foo" to bound click events', () => {
    const fixture = TestBed.createComponent(TestHostComponent);
    spyOn(fixture.componentInstance, 'handleClick');
    fixture.detectChanges();
    const myComponentElement = fixture.debugElement.query(By.directive(MyComponent));
    myComponentElement.click();

    expect(fixture.componentInstance.handleClick).toHaveBeenCalledWith('foo');
  });
});

@Component({
  template: '<my-component [linkText]="linkText" (click)="handleClick($event)"></my-component>',
})
class TestHostComponent {
  linkLabel: string;
  handleClick() {}
}

Whew!!! That was a lot of boilerplate. Here's just some of the issues:

  • Our TestBed module looks very similar if not identical to the NgModule I've probably already added MyComponent too. Total module duplication.
  • Since I've duplicated my module in my spec, I'm not actually sure the real module was setup correctly.
  • I've used REAL components and services in my spec which means I have not isolated the component I'm interested in testing.
    • This also means I have to follow, and provide all the dependencies of those real components to the TestBed module.
  • I had to create a TestHostComponent so I could pass bindings into my actual component.
  • My TestBed boilerplate code-length exceeded my actual test code-length.

The Solution

We should mock everything we can except for the component in test and that should be EASY. Our modules already define the environment in which our components live. They should be reused, not rebuilt in our specs.

Here's the same specs using shallow-render:

describe('MyComponent', () => {
  let shallow: Shallow<MyComponent>;

  beforeEach(() => {
    shallow = new Shallow(MyComponent, MyModule);
  });

  it('renders a link with the provided label text', async () => {
    const { find } = await shallow.render({ bind: { linkText: 'my text' } });
    // or shallow.render(`<my-component linkText="my text"></my-component>`);

    expect(find('a').nativeElement.textContent).toBe('my text');
  });

  it('sends "foo" to bound click events', async () => {
    const { element, outputs } = await shallow.render();
    element.click();

    expect(outputs.handleClick).toHaveBeenCalledWith('foo');
  });
});

Here's the difference:

  • Reuses (and verifies) MyModule contains your component and all its dependencies.
  • All components inside MyModule are mocked. This is what makes the rendering "shallow".
  • The tests have much less boilerplate which makes the specs easier to follow.
  • The HTML used to render the component is IN THE SPEC and easy to find.
    • This means specs now double examples of how to use your component.