Search code examples
angularunit-testingintegration-testingangular-componentstestbed

Unit testing (?) an angular 6 component with TestBed


When using the TestBed, are you really unit testing a component or are you making integration tests?

Creating a fixture (TestBed.createComponent(AppComponent)) and calling fixture.detectChanges() automatically calls ngOnInit. If you want to test another method, you are now testing multiple units.

This leads to another question: should you be testing units, or should you be testing user actions? For example, should you be testing the method setDimensions or should you be testing that when the user clicks on a certain button, an element has the appropriate dimensions amongst other things.

I guess the first way of testing would be closer to the "unit test" way, but then you still have to deal with the lifecycle methods of the component being called. This makes me think there is no way to do unit tests of a component using TestBed. Stubbing all lifecycle methods seems ridiculous.

Whichever way you decide to test, you should also test the DOM, should you not? Then you are not testing in isolation by including the DOM api.


Solution

  • As quoted from Angular docs:

    A component, unlike all other parts of an Angular application, combines an HTML template and a TypeScript class. The component truly is the template and the class working together. and to adequately test a component, you should test that they work together as intended.

    Such tests require creating the component's host element in the browser DOM, as Angular does, and investigating the component class's interaction with the DOM as described by its template.

    The Angular TestBed facilitates this kind of testing as you'll see in the sections below. But in many cases, testing the component class alone, without DOM involvement, can validate much of the component's behavior in an easier, more obvious way.

    So here, the unit is a component(the template and the class working together). And you should try to test a component by stubbing the inputs and dependencies.

    I guess if you read the testing docs once from top to bottom, you have answers for your questions in there.