1

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

2

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.