Angular Routing 组件测试

问题描述

我正在阅读来自 here 的角度路由测试的官方示例。我不明白 heroClick() 是如何触发点击的。

it('should tell ROUTER to navigate when hero clicked',() => {
  heroClick(); <------- how does this work !?  // trigger click on first inner <div class="hero">

  // args passed to router.navigateByUrl() spy
  const spy = router.navigateByUrl as jasmine.Spy;
  const navArgs = spy.calls.first().args[0];

  // expecting to navigate to id of the component's first hero
  const id = comp.heroes[0].id;
  expect(navArgs).toBe('/heroes/' + id,'should nav to HeroDetail for first hero');
});

这是 stackblitz 示例的link

解决方法

heroClick 是传递给第 84 行中的 tests() 函数的参数。它是一个不接受任何参数且不返回任何内容的函数。在第 120 行,heroClick() 调用传递给 tests() 的任何内容。

在第 27 和 48 行调用 tests(),传递不同的函数 clickForShallowclickForDeep,在它们的用法下方定义。这些函数通过与组件中的元素交互来模拟点击。