Search code examples
angulartestingjasminekarma-runner

some of your test did a full page reload


When i doing angular unit test,caught this error

ALERT: 'Add Success!' Chrome 58.0.3029 (Windows 10 0.0.0) ERROR Some of your tests did a full page reload! Chrome 58.0.3029 (Windows 10 0.0.0): Executed 0 of 1 ERROR (0.503 secs / 0 secs)

// strategyAdd.component.ts
export class StrategyAdd{

	strategy = new Strategy();
  status:string;
  iscookies = ['','Yes','No'];
  isuseragents = ['','Yes','No'];
  constructor( private strategyService: StrategyTablesService,
  						 private router:Router,
  			   		 private location: Location
  ) { }


  onClickCreate(strategy:Strategy):void {
    strategy.starttime = this.getDate();
  	this.strategyService.createStrategy(strategy).subscribe((data) => {
  		this.status = data.json().status;
  		if(this.status=="succeed"){
  			alert("Add Success!");
  			location.reload();
  		}else{
  			alert("Add failed!");
  		}
  	},
  	error => console.log(error));
  }
}

//// strategyAdd.component.spec.ts
class MockStrategyTablesService extends StrategyTablesService{
  //noinspection JSAnnotator
  createStrategy(strategy:Strategy){
    var mockData={
      "strategyid" : "12",
      "status" : "succeed"
    }
    return Observable.of({
      json:() => mockData
    });
  }
}
describe('override provide Service',()=>{
  let comp;
  let strategy = new Strategy();
  beforeEach(()=>{
    TestBed.configureTestingModule({
      imports:[HttpModule,RouterTestingModule],
      providers:[
        StrategyAdd,
        {provide:StrategyTablesService,useClass:MockStrategyTablesService},
        //{provide:Router,useClass:RouterStub},
        Location,
      ]
    });

  });

  beforeEach(inject([StrategyAdd],s => {
    comp = s;
  }));

  it('test onClickCreate',async(()=>{
    comp.onClickCreate(strategy);
    expect(comp.status).toEqual("success");
  }));
});


Solution

  • You do location.reload() and use real Location - so it will reload the page. Try to remove Location from providers array, since RouterTestingModule provides a stub Location already.