茉莉花测试无法识别功能getCurrentNavigation():this.router.getCurrentNavigation不是功能

问题描述 投票:1回答:1

[我正在尝试测试使用功能getCurrentNavigation()从导航获取数据的组件,当我将其与ng serve一起使用时,该组件运行正常,没有任何错误,但是我的测试是在说:

Component2Component>应该创建TypeError:this.router.getCurrentNavigation不是函数

这是我的组件为获取数据所做的事情:

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();
  });
});

为什么我的测试无法识别此功能?

angular jasmine
1个回答
0
投票

您在配置测试模块时提供的routerSpy不具有功能getCurrentNavigation。它包含的唯一功能是navigate,因为这是通过jasmine.createSpyObj创建它时定义的。

jasmine.createSpyObj

可以通过以下一行更改上面的行来解决问题。

const routerSpy = jasmine.createSpyObj('Router', ['navigate']);

const routerSpy = jasmine.createSpyObj('Router', ['getCurrentNavigation', 'navigate']); 做他的工作

RouterTestingModule设置要用于测试的路由器,并提供开箱即用的间谍实现。但是,您通过提供自己的RouterTestingModule覆盖了此内容。因此,您应该摆脱RouterTestingModule并按以下方式配置测试模块。

routerSpy

如果您需要在测试功能中的某处访问routerSpy,只需从TestBed.configureTestingModule({ declarations: [Component2Component], imports: [CommonModule, RouterTestingModule] }).compileComponents(); 中检索它,如下所示。

Router
© www.soinside.com 2019 - 2024. All rights reserved.