微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Angular 11 无法测试是否调用了 url

如何解决Angular 11 无法测试是否调用了 url

我在角度测试时遇到了问题。我想检测按钮点击时 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.
  • 堆栈上的另一个搜索 :p,我设法删除{ provide: Router,useValue: router } 但保留了 RouterTestingModule,我得到了:
Expected spy navigate to have been called with:
  [ [ '/my/route/call' ] ]
but it was never called.

console error

注意:我注意到删除 RouterTestingModule 时所有链接都没有呈现,所以我认为解决方案是实现结合 RouterTestingModule{ provide: Router,

  • 当我使用 (click) 而不是 routerLink效果很好,为什么?
<a id="signInButton" (click)="openNewPage()">Sign in</a>
openNewPage() {
  this.router.navigate(['/my/route/call']);
}

任何帮助都会很棒:) 提前致谢!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。