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);
});```
#Angular Unit Testing Tests Failing
7 messages · Page 1 of 1 (latest)
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.
Thank you for engaging on this issue. Why are none of my tests at least giving values?
I changed it to ```ts
routerSpy = jasmine.createSpyObj('Router', ['navigate']);
But end up with the same result
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.
Okay I will review that again. Thank you!