Amerigo Mancino
Posted on December 2, 2020
The topic of testing is always mistreated online. It's easy to check that on a hundred articles explaining how to develop a certain functionality, only one or two include a description of how to test it. Even in large projects and in big companies, it is not rare to just forget about testing because time is short or because workarounds are possible. This is a terrible behavior: the bigger the project, the easier it becomes to break something while implementing something else and - without unit tests - there is no way to know it for sure.
In this tutorial, I will explain you how to use ActivatedRoute
to pass a parameter from a component to another and how to mock it in the corresponding Unit Test.
How to pass a parameter with ActivatedRoute
Let's say we have a Home component where we display a list of users. Our goal is to pass the user id
via the web url, retrieve it and use it in a User component to collect - for example - all the user details:
To achieve that, first we need to define the route in app-routing.module.ts
as the following:
{
path: 'user/:id',
component: UserComponent
},
To pass the id we have two possibilities:
The first one is by editing the HTML in the Home component:
<a [routerLink]="['user', id]">
<!-- When clicked I redirect to the User component -->
</a>
The alternative is to navigate inside a typescript function; import the Router
and declare it in the constructor:
constructor(
private router: Router
) { }
Then use it in your function:
this.router.navigate(['/user', id]);
In the User component we can at last retrieve the id.
Let's import the ActivatedRoute
and declare it in the constructor:
constructor(
private activatedRoute: ActivatedRoute,
) { }
Afterwards in the ngOnInit()
we can get the id:
const id = this.activatedRoute.snapshot.params.id;
Once we have it, we can use it the way we like. For example, we can pass it as a parameter to a service and retrieve the User details as stated above.
Unit test
It is pretty straightforward to mock the ActivatedRoute
in the User component test file. All we have to do is to edit the providers
list as follows:
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ UserComponent ],
imports: [
RouterTestingModule,
HttpClientTestingModule
// ... whatever other module you have
],
providers:
[
{
provide: ActivatedRoute,
useValue: {
snapshot: {params: {id: '24fkzrw3487943uf358lovd'}}
}
}
]
})
.compileComponents();
}));
That's it!
Run npm test
in a terminal to execute all your unit tests and check the outcome!
Posted on December 2, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 18, 2024