Angular testing made easy with shallow rendering and easy mocking.

Docs

Articles

Angular Version Support

Angular shallow-render 10x 10x 9x 9x 6x-8x 8x 5x <= 7.2.0

Super Simple Tests

describe ( ' ColorLinkComponent ' , ) ;

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 ' , ) ; @ Component ( ) class TestHostComponent { ; 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.

I've probably already added 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.

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 ' , ) ;

Here's the difference: