#Angular Unit Testing Tests Failing

7 messages · Page 1 of 1 (latest)

regal wadi
#
describe('DroTaskCardComponent', () => {
  let component: DROTaskCardComponent;
  let fixture: ComponentFixture<DROTaskCardComponent>;
  let routerSpy: jasmine.SpyObj<Router>;
  let routeSpy: jasmine.SpyObj<ActivatedRoute>;
  let item: ITask<DROTarget>
  beforeEach(async () => {
    const dueDate = new Date();
    item = blah;
await TestBed.configureTestingModule({
      declarations: [ DROTaskCardComponent, Ellipsis, UserChip ],
      imports: [LoggerTestingModule, RouterTestingModule, HttpClientTestingModule, StoreModule.forRoot({my: testReducer })]
    })
    .compileComponents();

    fixture = TestBed.createComponent(DROTaskCardComponent);
    component = fixture.componentInstance;
    component.item = item;
    routerSpy = TestBed.inject(Router) as jasmine.SpyObj<Router>;
    routeSpy = TestBed.inject(ActivatedRoute) as jasmine.SpyObj<ActivatedRoute>;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
  it('should navigate to details page when allowDetailsPageClick is true', () => {
    component.allowDetailsPageClick = true;
    component.goToDetails(1);
    expect(routerSpy.navigate).toHaveBeenCalledWith(['/fulfillment/dro/details', 1], { relativeTo: routeSpy.root });
  });
  it('should convert the due date to a full date for calculation of time remaining', () => {
    const dueDate = new Date('2023-03-13');
    const expectedDate = new Date('2023-03-13T17:00:00');
    console.log("tesT" + component.getDueDate(dueDate).toString());
    expect(component.getDueDate(dueDate)).toEqual(expectedDate);
  });```
low galleon
#

As the message says, you expect the routerSpy.navigate to be a spied function, but it's not, because you've never made it a spied function.
The line TestBed.inject(Router) as jasmine.SpyObj<Router> means: "trust me, TypeScript compiler, inject() will return a SpyObj". But it won't, because you've never provided a SpyObj for this token. So you're just lying to yourself with this line.

regal wadi
#

Thank you for engaging on this issue. Why are none of my tests at least giving values?

regal wadi
#

But end up with the same result

low galleon
#

That creates a spy object, but in order for the component to get that spy object when Angular injects it, you must provide it in your testing module:

TestBed.configureTestingModule({
  ...,
  providers: [
    { provide: Router, useValue: routerSpy }
  ]
});

Read the chapter about testing of your book: it's all explained there.

regal wadi
#

Okay I will review that again. Thank you!