你如何模拟ActivatedRoute [英] How do you mock ActivatedRoute

查看:56
本文介绍了你如何模拟ActivatedRoute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular,我想做测试,但是我被困住了.我有一个功能:

I'm learning Angular and I want to do tests, but I'm stuck. I've got a function:

ngOnInit(): void {
    this.route.paramMap
    .switchMap((params: ParamMap) => 
        this.SomethingService.getSomething(params.get('id')))
        .subscribe(something => {
            this.something = something;
            this.doSomethingElse();
    });
}

其中

route: ActivatedRoute

我想测试一下,但我不知道如何模拟ActivatedRoute

and I want to test it but I don't know how to mock ActivatedRoute

推荐答案

模拟 ActivatedRoute 的一种简单方法是:

A simple way to mock ActivatedRoute is this one:

    TestBed.configureTestingModule({
      declarations: [YourComponenToTest],
      providers: [
        {
          provide: ActivatedRoute,
          useValue: {
            params: Observable.from([{id: 1}]),
          },
        },
      ]
    });

然后在您的测试中它将可用,并且您的功能应与此一起使用(至少在ActivatedRoute部分中起作用)

Then in your test it will be available and your function should work with this (at least the ActivatedRoute part)

如果要将其存储在变量中,则可以使用 it 函数中的 TestBed.get(ActivatedRoute)来获取它.

You can get it with TestBed.get(ActivatedRoute) in your it functions if you want to stock it in a variable.

别忘了从 rxjs/Rx 而不是从 rxjs/Observable

这篇关于你如何模拟ActivatedRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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