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

标签 angular jasmine

我正在尝试测试一个使用 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/

相关文章:

javascript - 如何模拟使用在 Node 模块中导出的导入(ES6 typescript)进行单元测试的外部注入(inject)库

Angular 单元测试 NullInjectorError : R3InjectorError(DynamicTestModule)[MatSnackBarComponent -> MatSnackBarComponent]:

Angular - 组件中订阅函数的单元测试

typescript - Gulp typescript tsconfig 与 Angular2

angular - Angular 2中的动态管道

javascript - Angular 5 httpClient 版本的代码

angularjs - 如何断言某个元素已获得焦点?

javascript - Angular 组件中注入(inject)的 stub 服务返回错误值

javascript - Angular 动态表单,包含从 JSON 获取的元素组

javascript - 在 Angular 中使用双向绑定(bind)时如何预选单选按钮?