Jasmine 测试无法识别函数 getCurrentNavigation():this.router.getCurrentNavigation 不是函数

Jasmine testing is not recognizing the function getCurrentNavigation(): this.router.getCurrentNavigation is not a function

我正在尝试测试使用功能 getCurrentNavigation() 从导航获取数据的组件,我的组件是 运行 通常没有任何错误,当我使用 ng serve 服务它时,但我的测试是:

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 设置用于测试的路由器并提供开箱即用的间谍实现。但是,您将通过提供自己的 routerSpy 来覆盖它。因此,你应该摆脱你的 routerSpy 并按如下方式配置测试模块。

TestBed.configureTestingModule({
  declarations: [Component2Component],
  imports: [CommonModule, RouterTestingModule]
}).compileComponents();

如果您需要访问测试函数中某处的 Router,只需从 TestBed 中检索它,如下所示。

it(test somethingcreate', () => {
  const router = TestBed.get(Router);
  ...
});

如果您正在搜索此错误并且您认为您正在正确地做事(使用 RouterTestingModule)但它仍然无法正常工作, 仔细检查你是否像我一样在你的导入数组中导入了 RouterTestingModule,而不是你的声明数组!