【问题标题】:Karma-Jasmine: TypeError: Cannot read properties of undefined (reading 'get')Karma-Jasmine:TypeError:无法读取未定义的属性(读取“get”)
【发布时间】:2021-12-17 18:30:08
【问题描述】:

我正在尝试为我的角度组件编写一个单元测试,但我遇到了这个错误。我在堆栈溢出和一些在线文档上对此进行了很多研究。这是我到目前为止没有运气尝试过的资源链接。

下面是我的代码

.ts 文件

export class SomeComponent implements OnInit {
  id = '--';
  
  constructor(
    private readonly someService: SomeService,
    private readonly utilsService: UtilsService,
    private readonly router: Router,
    readonly route: ActivatedRoute,
  ) {}

  ngOnInit() {
    this.id = this.route.snapshot.queryParamMap.get('id');
    this.getDetails();
  }

  viewInventory(){
    this.router.navigate(['..'], {
      relativeTo: this.route
    });
  }

  getDetails() {
    if (this.id) {
      this.getResourceOverview();
    }
  }

  getResourceOverview(): void {
    const resourceID = `search_keys=${"resource_id"}&search=${this.id}`
    this.resourceId = this.id
    this.someService
      .getResourceOverview(resourceID)
      .subscribe(
        (response) => {
          const result = response as any;
          if (result && something) {
            this.id = something  || '--';
          }
        },
        (error) => {
          console.log('Resource overview details failed with error', error);
        }
      );
  }
}

.ts.spec

class mockHttpWrapperService {
  readonly isApiReady = false;
}

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

  beforeEach(async(() => {
    activatedRouteSpy = {
      snapshot: {
        paramMap: convertToParamMap({
          id: 'dads123',
          code: 'IBM',
        })
      }
    };
    TestBed.configureTestingModule({
      declarations: [SomeComponent],
      imports: [
        SomeLibModule, CarbonModule, SomeModule.forRoot(),
        RouterModule.forRoot([])
      ],
      providers: [
        { provide: NGXLogger, useClass: MockNGXLogger },
        { provide: HttpWrapperService, useClass: mockHttpWrapperService },
        { provide: Router, useClass: class { navigate = jasmine.createSpy("navigate"); }},
        ApiContractService,
        TranslationService,
        ApiService,
        ApiContractService,
        TranslationService,
        SomeService,
        {
         provide: ActivatedRoute,
         useValue: activatedRouteSpy
        }
      ],
      schemas: [CUSTOM_ELEMENTS_SCHEMA],
    })
    .compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(SomeComponent);
      component = fixture.debugElement.componentInstance;
      fixture.detectChanges();
      component.ngOnInit();
    })
  }));

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

下面是错误信息

Chrome 93.0.4577 (Linux 0.0.0) SomeComponent should create 1  FAILED
TypeError: Cannot read properties of undefined (reading 'get')

【问题讨论】:

    标签: angular typescript unit-testing karma-jasmine angular9


    【解决方案1】:

    在您的测试设置中,您提供以下激活的路线:

    activatedRouteSpy = {
      snapshot: {
        paramMap: convertToParamMap({
          id: 'dads123',
          code: 'IBM',
        })
      }
    };
    

    在您的 ngOnInit 中,您可以像这样访问它:

    this.id = this.route.snapshot.queryParamMap.get('id');
    

    您的间谍没有queryParamMap 属性,而只有paramMap。在您的间谍中重命名它或同时提供paramMapqueryParamMap,如果您需要更进一步的话。

    【讨论】:

    • 我已在我的间谍中将其重命名为 queryParamMap。现在我收到此错误“ResourceOverviewComponent should create 1 FAILED Error: InvalidPipeArgument: ‘Unable to convert ‘Invalid Date’ into a date’ for pipe ‘DatePipe’”@pascalpuetz
    • 在您没有显示的模板中,似乎是一个获取无效参数的日期管道。在组件的 html 模板中,应该有类似 myVar | date 的内容,其中 myVar 包含无效日期。确保在测试期间模拟 myVar(或者实际上它被称为)变量。
    • 你能检查一下这个stackoverflow.com/questions/69879126/…@pascalpuetz
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 2018-02-02
    • 2017-04-28
    • 2020-09-04
    • 2021-04-29
    • 2021-12-01
    相关资源
    最近更新 更多