[英]Angular Testing RouterLink | Jasmine Test Infinite Loop
I'm creating a test for the Navbar component.我正在为 Navbar 组件创建一个测试。 When I test the button click on the logout key, Jasmine's test starts an infinite loop.
当我测试按钮单击注销键时,Jasmine 的测试开始无限循环。
describe('NavbarComponent', () => {
let component: NavbarComponent;
let fixture: ComponentFixture<NavbarComponent>;
let router: Router;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [ RouterTestingModule.withRoutes(
[{path: 'user', component: UserComponent},
{path: 'posts', component: PostsComponent},
{path: '', component: SigninComponent}
]
), HttpClientModule],
schemas: [NO_ERRORS_SCHEMA],
declarations: [NavbarComponent],
});
fixture = TestBed.createComponent(NavbarComponent);
component = fixture.componentInstance;
router = TestBed.get(Router);
});
Below is my test, I have already created other similar tests and they have not given me any problems.下面是我的测试,我已经创建了其他类似的测试,他们没有给我任何问题。 Could it be related to the logout page?
它可能与注销页面有关吗? Any tip will be appreciated!
任何提示将不胜感激!
fit('navigates to / when the "logout" button is clicked', fakeAsync(() => {
const navSpy = spyOn(router, 'navigateByUrl');
const buttons = fixture.debugElement.query(By.css('#logout'));
expect(buttons).toBeTruthy();
(buttons.nativeElement as HTMLButtonElement).click();
fixture.detectChanges();
tick();
expect(navSpy).toHaveBeenCalledWith(
router.createUrlTree(['/']),
jasmine.anything()
);
}));
After a few tries, I managed to find the solution.经过几次尝试,我设法找到了解决方案。 It was enough to create a method in the component.ts that redirected to the Login page.
在 component.ts 中创建一个重定向到登录页面的方法就足够了。 In this way, the test passed without any problems.
就这样,测试顺利通过了。 Of course, from the html I removed the router link that redirected to the login page and replaced it with a call to the method I built in the ts file.
当然,从 html 中,我删除了重定向到登录页面的路由器链接,并将其替换为对我在 ts 文件中构建的方法的调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.