Posts

Showing posts with the label jasmine

Angular 7 | RxJS : Test finalize()

In the following interceptor, I want to test if the method loaderService.stopLoading() is properly called : As you can see this function is called from the finalize() RxJS operator. The unit test for this interceptor is as follow: Thanks for sharing...

Angular 7: Test Error Interceptor

Testing an error interceptor can be a little tricky. Below is the code I want to test : Basically we need to perform an HTTP request and respond with a mocking error for testing this interceptor. You need also to register it in the TestBed.configureTestingModule . Thanks for sharing...

Angular 7: Test Guard

Image
I will show you how you can test a guard. I'd like to test the code below: We have in this code mainly 3 cases to test: The logged in user has the required role. He should be able to access the restricted area. The logged in user has NOT the required role. He should not be able to access the restricted area. The user is redirected to the home page. The user is NOT logged in. He should not be able to access the restricted area. The user is redirected to the login page. You can run your test with ng test . You should see something like that: Thanks for sharing...

Angular Testing: routerLink

Today, I'll show you how you can test such a code: The routerLink directive on the anchor tag give the router control over this element. Find more info here . A. Provide the routerTestingModule with dummy routes as: B. Declare  Router and Location for use in your test: C. Routing is an asynchronous activity so we use one of the asynchronous testing methods at our disposal, in this case the fakeAsync method. Happy coding!!!

Angular Testing: ActivatedRoute

The route information and parameters are available through the ActivatedRoute service. While testing your components, it may be good to mock this service. 1. Mock ActivatedRoute If the user select an item within a list, the snapshot strategy can be used in your detail component. The route.snapshot provides the initial value of the route parameter map. The parameters can be accessed this way: The mocking service: 2. How to use? First we need to make available our ActivatedRouteStub in our test and pass testing parameters. So, in your test: 3. Mocking ActivatedRoute using a factory Using a factory is somewhat easier. In our component we have this code which we'd like to test: The test below uses a fake ActivatedRoute registered with the useFactory : Thanks