首页 > 解决方案 > Angular 11:触发 a 的“激活”事件茉莉花测试中的元素

问题描述

我正在尝试编写一个尝试触发元素activate事件的测试。<router-outlet>这是我的设置:

应用路线:

const routes: Routes = [{
  path: 'path/for/component/:id',
  component: MyComponent,
  children: [
    { path: '', pathMatch: 'full', component: MySubComponent, outlet: 'outletname' }
  ]
}];

我的组件 HTML:

<mat-tab-group>
  <mat-tab label="Tab 1">
    <ng-template mat-tab-label>Tab 1</ng-template>
    <router-outlet name="outletname" (activate)="onActivate($event)"></router-outlet>
  </mat-tab>
  <mat-tab label="Tab 2">
    <!-- more content here -->
  </mat-tab>
</mat-tab-group>

我的组件 TS:

export class MyComponent {
  constructor(private route: ActivatedRoute) { }
  onActivate(obj: any): void { /* do the things */ }
}

我的组件规格:

describe('MyComponent', () => {
  let activatedRoute: ActivatedRoute;

  beforeAll(() => {
    activatedRoute = new ActivatedRoute();
  });

  beforeEach(() => {
    /* 
     * set activatedRoute properties such as URL and component to try
     * to get the onActivate() callback to fire on component render
     */
  });

  it('should test results of onActivate event', async () => {
    /*
     * 1. setup and construct the component
     * 2. test result of onActivate() callback
     */
  });
});

对于任何好奇的人,在完整组件实现中真正发生的所有事情都是activate回调只是通知MyComponent当前正在显示哪个选项卡,以便在用户在必要时导航到另一个选项卡时我可以抛出一个对话框。

我的问题是我无法弄清楚如何正确地模拟ActivatedRoute对象以 在我的测试中构造activate事件时触发事件。MyComponent据我了解,我在这里可能完全错了,<router-outlet>当当前路线与path我的路线列表中的 匹配时,应该触发。理想情况下,我想触发activate回调而不必在我的测试中明确调用它,即我不想component.onActivate(eventObj)在我的测试中说。我希望<router-outlet>只要ActivatedRoute有正确的信息,它就可以作为组件构造的一部分进行渲染。ActivatedRoute所以,问题是:必须在函数中指定多少beforeEach()才能获得<router-outlet>正确渲染?这甚至可能吗?我完全走错了吗?这是我想太多了吗?

我想最终使用一个ActivatedRoute模拟类而不是实际类来减少开销,并且只提供最少的必要功能来促进进一步的测试,但是我必须先让这个工作,然后才能正确抽象出一个实用程序类。

任何帮助将不胜感激!提前致谢!

标签: angulartypescriptjasmineangular-routerangular11

解决方案


推荐阅读