首页 > 解决方案 > 如何在 Jasmine 单元测试中模拟位置重定向,Angular?

问题描述

我想测试这个功能:

 onLinkClick() {
    if (this.congratsType === 'warning') {
      this.location.back();
    } else {
      window.location.href = this.urlNol;
    }
  }

我已经尝试过这个:

let loc: Location;  

  beforeEach(waitForAsync(() => {
    TestBed.configureTestingModule({
      declarations: [EndFlowComponent],
      providers: [
        { provide: location, useValue: window.history },
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    loc = jasmine.createSpyObj('Location', ['back']);
  });



    it(' redirect on Link click', () => {
        const congratsTypes = ['success', 'error' , 'info'];
        // tslint:disable-next-line: no-increment-decrement
        for (let i = 0; i < congratsTypes.length; i++) {
          component.congratsType = congratsTypes[i];
    
          component.onLinkClick();
          expect(loc.back).toHaveBeenCalledTimes(1);
        }
      })

当我运行测试时,浏览器重新定位到外部页面。但我想在不实际导航到该 URL 的情况下运行它。

标签: angularlocationkarma-jasminewindow.location

解决方案


推荐阅读