【问题标题】:How to set a route before a component is created in unit test如何在单元测试中创建组件之前设置路由
【发布时间】:2019-02-18 18:57:26
【问题描述】:

我有一个组件,它在创建时会从 url 中提取一个参数并启动一个查询。

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)
  }

我想对组件进行单元测试,但在TestBed 创建此组件之前,我不知道如何设置url。

网址应该是格式

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

我以为我可以在beforeEach 中设置路线,但那行不通

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();
  });

在上面的规范中,组件被创建但我没有得到 id。我尝试通过以下两种方式提取参数,但我总是得到null

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

和

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

我还在控制台中看到以下错误

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'

【问题讨论】:

    标签: angular6


    【解决方案1】:

    试试这个:

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

    或者:

    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_");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 1970-01-01
      • 1970-01-01
      • 2013-04-06
      相关资源
      最近更新 更多