Angular How to test window.location.href with jasmine, karma

Viewed 2090

In Angular project (Angular CLI: 9.1.4) I have a component with has function using window.location.href = EXTERNAL_URL

a.component.ts

import { Component, OnInit } from '@angular/core';
import { Service } from 'services/service';

@Component({
  selector: 'a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.scss']
})
export class AComponent implements OnInit {
  constructor(private service: Service) {}

  ngOnInit(): void {}

  redirect() {
    window.location.href = 'https://sample.com'
  }
}

For unit test, I have a.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { AComponent } from './A.component';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

describe('#AComponent', () => {
  let component: AComponent;
  let fixture: ComponentFixture<AComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientModule],
      declarations: [AComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(AComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();

  });

  describe('test', () => {
    it('test redirect function', () => {
      component.redirect();

      expect(window.location.href).toEqual('https://sample.com');
    });
  });
});

it must check the URL 'window.location.href' is same as I expected.

But when running test, showed error which says

Expected 'http://localhost:0987/context.html' to equal 'https://sample.com'

Why window.location.href param is like this?

Also, Karma (v5.0.4) showed test result on browser normally, but on this test, browser page is suddenly changed.

enter image description here

It happens because 'window.location.href' had run on test browser( it tried to open https://sample.com). But because of this redirection, I cannot see Karma result.

So, my question is

  • How can I test window.location.href
  • How can I stop redirection on karma test browser

P.S. I had thought that using window.location.href was not good, but I couldn't find any ways to redirect external URL.

1 Answers

Here the biggest problem is in the window object itself. But we can redefine it for the test environment. My solution:

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'a',
      templateUrl: './a.component.html',
      styleUrls: ['./a.component.scss']
    })
    export class AComponent {
      private window = window;

      constructor() {}

      redirect() {
        window.location.href = 'https://sample.com'
      }
    }

spec:

    import { async, ComponentFixture, TestBed } from '@angular/core/testing';
    
    import { AComponent } from './A.component';
    import { By } from '@angular/platform-browser';
    import { HttpClientModule } from '@angular/common/http';
    
    describe('#AComponent', () => {
      let component: AComponent;
      let fixture: ComponentFixture<AComponent>;
    
      beforeEach(async(() => {
        TestBed.configureTestingModule({
          imports: [HttpClientModule],
          declarations: [AComponent]
        }).compileComponents();
      }));
    
      beforeEach(() => {
        fixture = TestBed.createComponent(AComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      describe('test', () => {
        it('test redirect function', () => {
          let currentLocation;
          const windowStub = {
            location: {
             set href(value) { currentLocation = value;}
            }
          } as Window & typeof globalThis;
          component['window'] = windowStub;
          component.redirect();
    
          expect(currentLocation).toBe('https://sample.com');
        });
      });
    });
Related