问题描述
我在角度测试时遇到了问题。我想检测按钮点击时 url 何时更改。我在堆栈上关注了很多类似的问题,但自 1 周以来无法实现我的目标:/
说明
这是我的 HTML 模板:
<a id="signInButton" [routerLink]="['/my/route/call']">Sign in</a>
这是我的测试:
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']);
});
});
TypeError: Cannot read property 'root' of undefined
TypeError: Cannot read property 'detectChanges' of undefined
研究
- 在对堆栈进行一些研究之后,我设法从导入中删除了
RouterTestingModule
,现在我得到了:
Expected spy navigate to have been called with:
[ [ '/my/route/call' ] ]
but it was never called.
Expected spy navigate to have been called with:
[ [ '/my/route/call' ] ]
but it was never called.
注意:我注意到删除 RouterTestingModule
时所有链接都没有呈现,所以我认为解决方案是实现结合 RouterTestingModule
和 { provide: Router,
?
- 当我使用
(click)
而不是routerLink
时效果很好,为什么?
<a id="signInButton" (click)="openNewPage()">Sign in</a>
openNewPage() {
this.router.navigate(['/my/route/call']);
}
任何帮助都会很棒:) 提前致谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)