eran zizler
eran zizler

Reputation: 29

angular2 navigate to external URL(not a route url)

I am trying to find a way that I will able to navigate from my Angular2 application to some external URL.

route.navigate\route.navigateByUrl and location.go(common lib) - are set the url in the browser but nothing happened and no navigation occurred.

I dont want to use window.location solution.

also, I was able to achieve this goal by using location.href(lib.es6) but i was not able to mock this solution.

Is there any way that i can navigate to external URL and create unit test for this functionality? Thanks

Upvotes: 1

Views: 2477

Answers (1)

eran zizler
eran zizler

Reputation: 29

I investigated the above issue and found the right way to fix it. Using location.go(common lib) method can be used only for internal routing navigation and it will not work if we want to redirect to external URL( non Angular route link).

There is no way to mock native DOM elements\attributes ( unlike functions ) like : window.location OR location.href(lib.es6).

My solution is to configure Location service that has few methods like: go, path and home. Each method should use the lib.es6 location to invoke the required methods. For example: LocationService.go(url) will invoke: location.href = url

Note: This service will be used in all places that need external URL redirections. Mocking location service on .spec files will be handled by:

Declare Location Service:

const locationSpy: LocationService = new LocationService();

Inject Mocked service as a provider:

In the TestBed.configureTestingModule add:

providers: [
    {provide: LocationService, useValue: locationSpy}
  ]

Defined SpyOn on the mocked method that we using:

spyOn(locationSpy, 'go');

Test external redirection call:

expect(locationSpy.go).toHaveBeenCalledWith('expected URL');

Thanks Eran

Upvotes: 1

Related Questions