【问题标题】:No provider for ActivatedRouteSnapshotActivatedRouteSnapshot 没有提供者
【发布时间】:2021-08-25 15:10:29
【问题描述】:

我有这样的组件

      constructor(
        private route: ActivatedRoute) {
      }
      ngOnInit(): void {
        console.log(this.route.snapshot.params.user);
        console.log(this.route.snapshot.params.id);
      }

我在创建这样的测试时得到了

    describe('OKComponent', () => {
      let component: OKComponent;
      let fixture: ComponentFixture<OKComponent>;
    
      beforeEach(async () => {
        await TestBed.configureTestingModule({
          imports: [RouterTestingModule],
          declarations: [
            OKComponent
          ],
          providers: [
            {
              provide: ActivatedRoute,
              useValue: {
                snapshot: {
                  params: {
                    user: '',
                    id: ''
                  }
                },
                url: of({})
              }
            }
          ]
        })
          .compileComponents();
      });
    
      beforeEach(() => {
        fixture = TestBed.createComponent(OKComponent);
        component = fixture.componentInstance;
        TestBed.inject(ActivatedRouteSnapshot);
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });

我总是遇到的错误 NullInjectorError: R3InjectorError(CompilerModule)[ActivatedRouteSnapshot -> ActivatedRouteSnapshot]: NullInjectorError:ActivatedRouteSnapshot 没有提供程序! 错误属性:对象({ ngTempTokenPath:null,ngTokenPath:['ActivatedRouteSnapshot','ActivatedRouteSnapshot']}) NullInjectorError: R3InjectorError(CompilerModule)[ActivatedRouteSnapshot -> ActivatedRouteSnapshot]:

我查看了所有其他解决方案,但没有解决我的错误

【问题讨论】:

  • 您在提供者下有ActivatedRoute。您是否尝试明确提供ActivatedRouteSnapshot
  • 这是你需要的我认为TestBed.inject(ActivatedRoute);请尝试

标签: angular unit-testing jasmine


【解决方案1】:

就像JsNgian 说尝试TestBed.inject(ActivatedRoute); 一样,你可以摆脱这条线,因为你没有将它分配给任何东西。

试试这个:

beforeEach(() => {
        fixture = TestBed.createComponent(OKComponent);
        component = fixture.componentInstance;
        // Delete the line bellow, you don't need it.
        // TestBed.inject(ActivatedRouteSnapshot);
        fixture.detectChanges();
      });

【讨论】:

    猜你喜欢
    • 2017-08-13
    • 2021-05-06
    • 2019-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多