2

我遇到了角度测试的问题。我想检测按钮单击时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.

控制台错误

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

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

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

4

0 回答 0