I had a problem with angular testing. I want to detect when an url change on a button click. I followed a lot of similar issues on stack but can't achieve to my goal since 1 one week :/
Explanation
Here is my HTML template:
<a id="signInButton" [routerLink]="['/my/route/call']">Sign in</a>
Here is my test:
describe('MyComponent', () => {
let component: MyComponent;
let fixture: ComponentFixture< MyComponent >;
let httpMock: HttpTestingController;
// Creating mocked router here
const router = {
navigate: jasmine.createSpy('navigate'),
};
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [MyComponent],
imports: [
RouterTestingModule,
HttpClientTestingModule,
DatabaseModule.forRoot(),
FormsModule,
ReactiveFormsModule,
],
providers: [
MyComponentService,
{ provide: Router, useValue: router },
],
}).compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(MyComponent);
component = fixture.componentInstance;
});
beforeEach(() => (httpMock = TestBed.inject(HttpTestingController)));
afterEach(() => {
router.navigate.calls.reset();
httpMock.verify();
});
fit('should redirect on sign in click', async () => {
fixture.detectChanges();
const signInButton = fixture.debugElement.nativeElement.querySelector(
'#signInButton'
);
signInButton.click();
fixture.detectChanges();
await fixture.whenStable();
// impossible to pass this step :/
expect(router.navigate).toHaveBeenCalledWith(['/my/route/call']);
});
});
When I run the test, I have two errors:
TypeError: Cannot read property 'root' of undefined
TypeError: Cannot read property 'detectChanges' of undefined
Researchs
- After some research on stack, I managed to remove
RouterTestingModule
from imports and now I'm getting:
Expected spy navigate to have been called with:
[ [ '/my/route/call' ] ]
but it was never called.
- Another searches on stack :p, I managed to remove
{ provide: Router, useValue: router }
but keepRouterTestingModule
and I'm getting:
Expected spy navigate to have been called with:
[ [ '/my/route/call' ] ]
but it was never called.
NOTE: I noticed that all link are not rendered when I'm removing RouterTestingModule
, so I think the solution is to achieve to combine RouterTestingModule
and { provide: Router, useValue: router },
?
- When I use a
(click)
instead ofrouterLink
it's working well, why ?
<a id="signInButton" (click)="openNewPage()">Sign in</a>
openNewPage() {
this.router.navigate(['/my/route/call']);
}
Any help would be amazing :) Thanks in advance !
Aucun commentaire:
Enregistrer un commentaire