我正在尝试在我的 Angular 应用程序中进行一些测试,但是当我使用 routerLink 添加这一行时,测试给出了错误:
<a class="nav-link" routerLink="../loja-lista" role="tab" type="button">
<fa-icon [icon]="faArrowLeft" style="font-size: x-large; color: #225262"> </fa-icon>
</a>
package.json:
"@angular/common": "^15.2.9",
"@angular/compiler": "^15.2.9",
"@angular/core": "^15.2.9",
...
...
"jasmine-core": "~4.0.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.1.0",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "~1.7.0",
错误
TypeError: Cannot read properties of undefined (reading 'events')
TypeError: Cannot read properties of undefined (reading 'events')
at new RouterLink (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/router/fesm2020/router.mjs:5711:40)
at NodeInjectorFactory.factory (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/router/fesm2020/router.mjs:5865:16)
at getNodeInjectable (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2020/core.mjs:3431:44)
...
这是我的四个测试,在模板中没有 RouterLink 的情况下也能正常工作:
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule } from '@angular/common/http/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { ActivatedRoute, Router } from '@angular/router';
import { LOJAApi } from 'my-lib';
import { EdicaoComponent } from './edicao.component';
describe('EdicaoComponent', () => {
let component: EdicaoComponent;
let fixture: ComponentFixture<EdicaoComponent>;
let lojaService: LOJAApi;
let router: Router;
let route: ActivatedRoute;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule, EdicaoComponent],
providers: [
{ provide: LOJAApi, useValue: lojaService },
{ provide: Router, useValue: router },
{ provide: ActivatedRoute, useValue: route },
],
}).compileComponents();
fixture = TestBed.createComponent(EdicaoComponent);
component = fixture.componentInstance;
lojaService = TestBed.inject(LOJAApi);
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should return all phone info', () => {
component.edicaoForm.value.DDD_FONE = null;
component.edicaoForm.value.FONE = null;
expect(component.getPhone()).toBe('00 000000000');
});
it('should return DDD', () => {
component.edicaoForm.value.TELEFONE = '11999999999';
expect(component.handleDDD()).toBe('11');
});
it('should return phone', () => {
component.edicaoForm.value.TELEFONE = '11999999999';
expect(component.handlePhone()).toBe('999999999');
});
});
您的 routerLink 上缺少括号。