How to set a route before a component is created in unit test

跟風遠走 提交于 2019-12-11 17:09:03

问题


I have a component which when created extracts a parameter from url and launches a query.

ngOnInit() {
   ....
 this.id = this.route.snapshot.paramMap.get("my-id");
    console.log("will query db for question with id " + this.id);
    this.myService.getId(this.id)
  }

I want to unit-test the component but I can't figure out how to set the url before TestBed creates this component.

The url should be of format

{
    path:'id-details;my-id=:id',//  for eg id-details;my-id=1 
    component:MyComponent
  },

I thought I could set the route in beforeEach but that isn't working

beforeEach((done) => {
    fixture = TestBed.createComponent(MyComponent);
    component = fixture.componentInstance;
    let router = TestBed.get(Router);
    let location = TestBed.get(Location);
    router.navigateByUrl("/id-details;my-id=1");
  });

  fit('should create', () => {
    expect(component).toBeTruthy();
  });

In above spec, the component gets created but I don't get id. I tried extracting params in the followinng two ways but I always get null

 this.id = this.route.snapshot.paramMap.get("my-id"); //get null

and

 this.id = this.route.snapshot.paramMap.get("id-details"); //get null

I also see the following error in the console

context.js:1972 Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?
Unhandled Promise rejection: Cannot match any routes. URL Segment: 'question-details;question-id=1' ; Zone: ProxyZone ; Task: Promise.then ; Value: Error: Cannot match any routes. URL Segment: 'question-details;question-id=1'

回答1:


Try this:

 spyOn(component.route.snapshot.paramMap,"get").and.returnValue("some_id")

Or:

let fake_value = "value";
spyOn(component.route.snapshot.paramMap,"get").and.callFake(()=>{
    return fake_value;
});

fake_value = "another";
component.someMethod();
expect(...).toBe("another");

fake_value = "then_";
component.someMethod();
expect(...).toBe("then_");


来源:https://stackoverflow.com/questions/54753695/how-to-set-a-route-before-a-component-is-created-in-unit-test

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!