如何在单元测试中创建组件之前设置路由 [英] How to set a route before a component is created in unit test

查看:23
本文介绍了如何在单元测试中创建组件之前设置路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

网址应符合格式

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

我以为我可以在 beforeEach 中设置路线,但这不起作用

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

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

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

 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'

推荐答案

试试这个:

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

这篇关于如何在单元测试中创建组件之前设置路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆