Angular 4 - 失败:无法解析ActivatedRoute的所有参数:(?,?,?,?,?,?,?,?)

时间:2018-01-03 12:46:24

标签: angular unit-testing karma-jasmine router testbed

我已经提到了以下链接来获取答案,但我找不到任何适用于我的方案的解决方案。 Error: (SystemJS) Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?)

因此,我一直试图从供应商处移除激活路线,但测试床仍未通过。它显示

  

错误:没有ActivatedRoute的提供者!

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

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

获取

时出错

enter image description here

3 个答案:

答案 0 :(得分:34)

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

describe('SomeComponent', () => {

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

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

答案 1 :(得分:0)

{
  provide: ActivatedRoute,
  useValue: {
    snapshot: {
      queryParamMap: {
        get(): number {
          return 6;
        }
      }
    }
  }
}

答案 2 :(得分:0)

这是7号角的解决方案

{
    provide: ActivatedRoute,
    useValue: {
        snapshot: {
            paramMap: {
                get(): string {
                    return '123';
                },
            },
        },
    },
},