我正在尝试测试一个使用 getCurrentNavigation()
功能从导航中获取数据的组件,当我使用 ngserve< 提供服务时,我的组件运行正常,没有任何错误
,但我的测试表明:
Component2Component > should create TypeError: this.router.getCurrentNavigation is not a function
这就是我的组件获取数据的方法:
constructor(public router: Router) {
if (
this.router.getCurrentNavigation() &&
this.router.getCurrentNavigation().extras
) {
console.log(this.router.getCurrentNavigation().extras);
}
这是我的测试:
describe('Component2Component', () => {
let component: Component2Component;
let fixture: ComponentFixture<Component2Component>;
const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [Component2Component],
imports: [CommonModule, RouterTestingModule],
providers: [{ provide: Router, useValue: routerSpy }]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(Component2Component);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
为什么我的测试无法识别这个功能?
最佳答案
您在配置测试模块时提供的routerSpy
没有函数getCurrentNavigation
。它包含的唯一函数是 navigate
因为这是您在通过 jasmine.createSpyObj
创建它时定义的函数。 。
const routerSpy = jasmine.createSpyObj('Router', ['navigate']);
可以通过将上面的行更改为以下行来解决该问题。
const routerSpy = jasmine.createSpyObj('Router', ['getCurrentNavigation', 'navigate']);
让 RouterTestingModule
完成其工作
RouterTestingModule
设置用于测试的路由器并提供开箱即用的 spy 实现。然而,您可以通过提供自己的 routerSpy
来覆盖它。因此,您应该摆脱 routerSpy
并按如下方式配置测试模块。
TestBed.configureTestingModule({
declarations: [Component2Component],
imports: [CommonModule, RouterTestingModule]
}).compileComponents();
如果您需要访问测试函数中某处的Router
,只需从TestBed
检索它,如下所示。
it(test somethingcreate', () => {
const router = TestBed.get(Router);
...
});
关于angular - Jasmine 测试无法识别函数 getCurrentNavigation() : this. router.getCurrentNavigation 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61980275/