36

我已参考以下链接来获得答案,但我找不到适合我的方案的任何有效解决方案。 错误:(SystemJS)无法解析ActivatedRoute的所有参数:(?,?,?,?,?,?,?,?)

因此,我一直在尝试从提供程序中删除激活的路由,但测试台仍然没有通过。表明

错误:ActivatedRoute 没有提供者!

所以这是我的代码,我想在使用Jasmine 的 Angular 应用程序中运行我的测试台。

import { ActivatedRoute } from '@angular/router';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RouterModule, Routes } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';

describe('SomeComponent', () => {
  let component: SomeComponent;
  let fixture: ComponentFixture<SomeComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({ 
      imports: [ RouterModule, RouterTestingModule ],
      declarations: [ SomeComponent ],
      providers: [ ActivatedRoute ],
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(SomeComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

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

获取错误

在此处输入图像描述

4

3 回答 3

58

您想向您的组件注入一个假的 ActivatedRoute,因为您在测试中自己创建了它,因此路由器不会为您创建它并注入一个 ActivatedRoute。所以你可以使用这样的东西:

describe('SomeComponent', () => {

  const fakeActivatedRoute = {
    snapshot: { data: { ... } }
  } as ActivatedRoute;

  beforeEach(async(() => {
    TestBed.configureTestingModule({ 
      imports: [ RouterTestingModule ],
      declarations: [ SomeComponent ],
      providers: [ {provide: ActivatedRoute, useValue: fakeActivatedRoute} ],
    })
    .compileComponents();
  }));
});
于 2018-01-03T12:54:54.923 回答
12

这是角度7的解决方案

{
    provide: ActivatedRoute,
    useValue: {
        snapshot: {
            paramMap: {
                get(): string {
                    return '123';
                },
            },
        },
    },
},
于 2019-07-17T12:36:30.927 回答
5
{
  provide: ActivatedRoute,
  useValue: {
    snapshot: {
      queryParamMap: {
        get(): number {
          return 6;
        }
      }
    }
  }
}
于 2019-07-17T08:41:28.847 回答