本文介绍了使用Snapshot和ParamMap的Angular Mock ActivatedRoute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用它,来自此处 :

I'm using this, from here:

constructor(private heroService: HeroService,
    private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
    const heroId = this.activatedRoute.snapshot.paramMap.get('id');
    this.heroService.getHeroById(heroId).subscribe((hero: Hero) => {
        ...
    });
}

现在我有一个单元测试,需要模拟此ActivatedRoute.我已经在stackoverflow中检查了一些答案,但是没有运气.

Now I have a unit test that needs to mock this ActivatedRoute. I've already check some answers here in stackoverflow but without luck.

请注意,我使用的是snapshot.paramMap ,因此许多解决方案根本无法使用.例如,,以及不起作用.

Notice that I'm using snapshot.paramMap so many solutions do not work at all. For example, this, this, and this do not work.

我认为接近有效的答案可能是:

I think the near valid answer could be:

{
    provide: ActivatedRoute,
    useValue: {paramMap: Observable.of(convertToParamMap({id: 1}))}
}

但也不起作用.

显示的错误是:

Error: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'ng:///HeroesModule/HeroDetailComponent_Host.ngfactory.js'.
    error properties: Object({ INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25, code: 19 })

这是因为我正在执行一个请求,该请求的状态为500,因为 paramMap未定义,因此该请求上没有id.

This is because I'm doing a request that responses with status 500 because paramMap is undefined so there is no id on the request.

...有什么想法吗?

... any ideas?

感谢和BR

推荐答案

将快照添加到useValue中,例如:

Add snapshot to the useValue like:

{
          provide: ActivatedRoute,
          useValue: {
            snapshot: {
              paramMap: convertToParamMap({
                id: '1'
              })
            }
          }
        }

这篇关于使用Snapshot和ParamMap的Angular Mock ActivatedRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-16 23:44