Repository navigation
Survival guide for unit testing in Angular
"your map through the labyrinth"
Angular provides a great set of tools for use in unit testing. The tools are designed to provide ways to mock the Angular framework, providing a light and flexible way to unit test your components and services. However, along the way, there are many pitfalls and traps laid out before you. From timing issues to chaining dependencies, it is easy to become frustrated and lost.
This guide aims to provide some insight and tips that could help you when navigating the labyrinth.
When you want to test a component, the component often has dependencies that are being injected by Angular.
export class ReallyCoolWorkQueueComponent {
constructor(
private userPermissionsService: UserPermissionsService,
...If you run the tests without providing those dependencies in the TestBed, you will receive an error during the build of the tests indicating that those dependencies are missing, and you will most likely add them. But what if the UserPermissionsService also depends on the CurrentUserService? Would you also provide that? What if then the CurrentUserService depends on the CookieService?
This is the "dependency chain trap" and it is often the first trap you run into when writing unit tests in Angular. You are trying to test the functionality of the ReallyCoolWorkQueueComponent. So the best way to avoid this trap is to focus on your objective. If you are testing the component, and the component needs some service as a dependency, does it need the real service? Couldn't you instead provide a mock?
// don't do this
TestBed.configureTestingModule({
...
providers: [
UserPermissionsService,
...
// do this
TestBed.configureTestingModule({
...
providers: [
{ provide: UserPermissionsService, useClass: MockUserPermissionsService },
...Using mocks for the component's dependencies is a great way to limit the scope of your tests while breaking the dependency chain right at the start. It puts you in full control of the circumstances outside of the component, so that you can test the scenario in a controlled environment.
Mocks are incredibly helpful when doing unit testing. They're even "the" answer for avoiding a lot of other traps. But even they can be dangerous.
// excerpt from mock-work-item.service.ts
export class MockWorkItemService extends WorkItemService {
getById(id: number): Observable<IWorkItem> {
return of(getMockWorkItem());
}
}Above is an example of a mocked service that extends the original and then overwrites one of it's methods to return some mocked data. Presumably, that's the only method your unit tests will access. However if your tests do use something else from MockWorkItemService, it wouldn't error, because you have extended the entire original service. But that's not really controlling all aspects of the Mock, is it?
While this method can work, there are several disadvantages here. The biggest of which is if you would like to return something different, you would build a whole different mock.
This can easily lead to the "drowning in mocks trap" where you have more mocks than you have spec files, and maintaining those mocks and knowing which one to use in which situation can get very cumbersome. Also, since you have good code separation and are keeping the mocks in separate files, you now have to leave the spec file to figure out what to expect being returned from the mock.
It's great type safety to build things things way, but keep in mind that you aren't building here. You're testing. And that's when it's usually better to be lean.
// for simple mocks where only one or two methods are being mocked
// don't do this
TestBed.configureTestingModule({
...
providers: [
{ provide: WorkItemService, useClass: MockWorkItemService },
...
// do this
TestBed.configureTestingModule({
...
providers: [
{ provide: WorkItemService, useValue: { getById: () => null } },
...
// and then in your tests do something like this
// where you set the return value you want to mock
// in the spy itself
it('should call getById', () => {
mockWorkItem = getMockWorkItem();
component.selectedWorkItemId = mockWorkItem.Id;
spyOn(service, 'getById').and.returnValue(of(mockWorkItem));
component.getSelectedWorkItem();
expect(service.getById).toHaveBeenCalledWith(mockWorkItem.Id);
});There are usually only a few cases where you need a more robust mock, and usually the above method can work. It has the benefits of being compact, straight forward, and defined right at the test where it is used.
In order to test your components and services, you will often have to provide data for them to work with.
const mockWorkItem: IWorkItem = {
Active: true,
...
}
...
it('should toggle work item active', () => {
component.selectedWorkItem = mockWorkItem;
const expectedValue = !component.selectedWorkItem.Active
component.toggleActive();
expect(component.selectedWorkItem.Active).toEqual(expectedValue);
});The above test will work as expected in isolation, but only the items inside the it block are in isolation. The mockWorkItem is not in isolation and can be mutated by each test that runs it. Thus, if the mockWorkItem is used in multiple tests, it may be altered by a previous test, affecting how it works in the current test.
This is the "mock object trap" and it is a very sneaky one at that, since it can pass on the first run of the tests, and then fail on the next run. This is due to the tests not having a guaranteed order and them running asynchronously. Luckily, there is an easy fix for this one. Just don't define objects.
You can avoid defining objects by using functions to return anonymous objects, which ensures each time you reference the object using the function, you are receiving a new instance of the object.
function getMockWorkItem(): IWorkItem {
return {
Active: true,
...
}
}
...
it('should toggle work item active', () => {
component.selectedWorkItem = getMockWorkItem();
const expectedValue = !component.selectedWorkItem.Active
component.toggleActive();
expect(component.selectedWorkItem.Active).toEqual(expectedValue);
});There are of course other ways to break references to the original object, such as using a spread operator {...mockWorkItem} or using JSON.parse(JSON.stringify(mockWorkItem)). These options require that each time you go to use the object, that you remember to do these tricks to break the reference. Also the spread operator doesn't work as expected for deeply nested properties. Make either of these mistakes, and it could be a nightmare to track down. The "objects from functions" method ensures that every use is going to get a new object while also reducing the chance for errors.
While testing a component, it can be tempting to run the TestBed fixture's detectChanges method.
beforeEach(() => {
TestBed.configureTestingModule({
...
});
fixture = TestBed.createComponent(ReallyCoolWorkQueueComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});By running detectChanges the component springs to life, going through the same lifecycle that component would go through when used in your application. It runs it's constructor, ngOnInit and other lifecycle hooks, and parses the template. This can be useful in limited examples.
If your unit tests require checks in the template, than this is really the only way to go. But most of the time, you won't be checking the template for updates or changes. Unit testing should be specific to your component, and not testing the Angular frameworks ability to manipulate the DOM. For instance, if you have a property named as showDeleteButton you don't need to check if the button with an ngIf on it is present or not. You just need to know if the property showDeleteButton is true or false.
Most unit tests are testing the functionality inside of your .ts file, not the .html template. In these cases, parsing the template is really a wasted effort with its own set of complications. Imagine your component is making use of other custom components you have built. The TestBed won't know how to parse those components, since you haven't imported them. So now you have to either import those components, and anything they need, or create a mock of the component. Worst of all, this issue doesn't help you to unit test your component, it's just getting in the way and creating extra work.
This is the "fixture.detectChanges" trap and the best way to fix this is to not use detectChanges unless you truly need it. If you think you need it, interrogate that assumption. Do you really need it? Could you get away with just calling ngOnInit and/or any other lifecycle hooks directly?
// don't do this
beforeEach(() => {
TestBed.configureTestingModule({
...
});
fixture = TestBed.createComponent(ReallyCoolWorkQueueComponent);
component = fixture.componentInstance;
fixture.detectChanges(); // parses the template causing more imports, declarations, mocks
});
// do this
beforeEach(() => {
TestBed.configureTestingModule({
...
});
fixture = TestBed.createComponent(ReallyCoolWorkQueueComponent);
component = fixture.componentInstance;
component.ngOnInit(); // call the methods you want to run directly rather than forcing the component to run it's lifecycle
});There may be times when you need to work with the template and/or simulate Angular change detection, and for these you will need to employ the fixture's detectChanges method. But most of the time, you won't. So it is best to start off assuming you won't need it.