3

I am trying to write a unit test for my angular component and I am stuck at this error. I have researched a lot about this on stack overflow and some online docs. Here is the link of resources which I have tried so far with no luck.

Below is my code

.ts file

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

And below is the error message

Chrome 93.0.4577 (Linux 0.0.0) SomeComponent should create 1  FAILED
TypeError: Cannot read properties of undefined (reading 'get')
glennsl
  • 28,186
  • 12
  • 57
  • 75
Amir
  • 103
  • 1
  • 2
  • 10

1 Answers1

3

In your test setup you provide the following activated route:

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

And in your ngOnInit you access it like this:

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

Your spy does not have a queryParamMap property, but only a paramMap. Rename it in your spy or supply both, the paramMap and a queryParamMap if you need both further down the line.

pascalpuetz
  • 5,238
  • 1
  • 13
  • 26
  • I have renamed it to queryParamMap in my spy. And now I am getting this error "ResourceOverviewComponent should create 1 FAILED Error: InvalidPipeArgument: 'Unable to convert "Invalid Date" into a date' for pipe 'DatePipe'" @pascalpuetz – Amir Nov 03 '21 at 11:23
  • In your template, which you didn't show, seems to be a date pipe that is getting an invalid argument. In your component's html template, there should be something along the lines of `myVar | date` where `myVar` contains an invalid date. Make sure to mock the `myVar` (or however it's actually called) variable during testing. – pascalpuetz Nov 03 '21 at 12:13
  • Could you please check this https://stackoverflow.com/questions/69879126/fixture-detectchanges-method-resulting-in-test-case-to-fail @pascalpuetz – Amir Nov 08 '21 at 06:10