Skip to content

Instantly share code, notes, and snippets.

@mindscratch
Created December 31, 2020 17:35
Show Gist options
  • Save mindscratch/c56cbbe106a3021aedadbf8338e481ee to your computer and use it in GitHub Desktop.
Save mindscratch/c56cbbe106a3021aedadbf8338e481ee to your computer and use it in GitHub Desktop.
Angular + Jest Mock Window Location
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { TestBed } from '@angular/core/testing';
import { WindowLocationToken } from '../location';
import { LocationHrefGuard } from './location-href.guard';
describe('LocationHrefGuard', () => {
let guard: LocationHrefGuard;
const routeMock: any = {
snapshot: {},
data: { pathname: '/app/logout.php' },
};
const routeStateMock: any = { snapshot: {}, url: '/logout' };
const locationMock = {
href: 'http://test.com/app/test.php',
pathname: '/app/test/php',
assign: jest.fn(),
};
const expectedUrl = 'http://test.com/app/logout.php';
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
LocationHrefGuard,
{
provide: WindowLocationToken,
useFactory: () => locationMock,
},
],
imports: [HttpClientTestingModule],
});
guard = TestBed.inject(LocationHrefGuard);
});
test('should be created', () => {
expect(guard).toBeTruthy();
});
test('should navigate to new url', () => {
expect(guard.canActivate(routeMock, routeStateMock)).toEqual(false);
expect(locationMock.assign).toHaveBeenCalled();
});
});
@Injectable({
providedIn: 'root',
})
/**
* A guard that navigates to a new url.
*/
export class LocationHrefGuard implements CanActivate {
constructor(@Inject(WindowLocationToken) private location: Location) {}
canActivate(
route: ActivatedRouteSnapshot,
state: RouterStateSnapshot
):
| Observable<boolean | UrlTree>
| Promise<boolean | UrlTree>
| boolean
| UrlTree {
const newPath = route.data['pathname'];
const newUrl = location.href.replace(location.pathname, newPath);
location.assign(newUrl);
return false;
}
}
import { InjectionToken } from '@angular/core';
export const WindowLocationToken = new InjectionToken('Window Location');
export function windowLocationProvider() {
return window.location;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment