首页 > 解决方案 > 使用 Jasmine 在路由和 routerLink 中进行角单元测试

问题描述

我是 Angular 和单元测试的新手。我创建了一个用于在 Angular 中测试路由的新项目。我按照Angular 官方文档中的指南进行操作。它在测试 routerLink 时确实有效。

但这是一个问题。我忘记在 app.routing.module.ts 中创建路由,但测试仍然通过。

这是 routing.module.ts 中的代码

const routes: Routes = [];

并在 html <a routerLink="/order">Order</a><br/> <a routerLink="/creditCard">Credit Card</a>

在spec.ts

describe('AppComponent', () => {
  let fixture: ComponentFixture<AppComponent>;
  let app: any;
  let compiled: any;
  let linkDes:any;
  let routerLinks:any;
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        RouterTestingModule
      ],
      declarations: [
        AppComponent,
        RouterLinkDirectiveStub
      ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(AppComponent);
      app = fixture.debugElement.componentInstance;
      fixture.detectChanges();
      compiled = fixture.debugElement.nativeElement;

      // find DebugElements with an attached RouterLinkStubDirective
      linkDes = fixture.debugElement
        .queryAll(By.directive(RouterLinkDirectiveStub));

      // get attached link directive instances
      // using each DebugElement's injector
      routerLinks = linkDes.map(de => de.injector.get(RouterLinkDirectiveStub));
    })
  }));

  it('should create the app', () => {
    expect(app).toBeTruthy();
  });

  it(`should have as title 'unitTesting'`, () => {
    expect(app.title).toEqual('unitTesting');
  });

  it('should render title in a h1 tag', () => {
    expect(compiled.querySelector('h1').textContent).toContain('Welcome to unitTesting!');
  });

  it('can get RouterLinks from page', () => {
    expect(routerLinks.length).toBe(2, 'should have 2 routerLinks');
    expect(routerLinks[0].linkParams).toBe('/order');
    expect(routerLinks[1].linkParams).toBe('/creditCard');
  });

}); 

我理解单元测试应该被隔离。但在某些情况下,它应该有连接才能进行测试。

我用谷歌搜索。但是很多答案只是与静态路径进行比较。

我的问题是,如何在如下场景中进行测试:

  1. 在路由.module.ts

    常量路线:路线= [

    {path:"order",component:OrderComponent}, {path:"creditCard",component:CreditcardComponent}

    ];

2.在两个或多个页面中具有相同的锚标签 <a routerLink="/order">Order</a><br/> <a routerLink="/creditCard">Credit Card</a>

3.如果有人改变了routing.module.ts中的路径,比如

{path:"orderDetail",component:OrderComponent},

并且忘记在所有或一个 html 文件中更改 routerLink 的路径,对于那些忘记更改 routerLink 路径的组件,测试用例仍将通过。

因此,如何修复它以在测试用例中显示失败。

标签: angularunit-testingroutingjasmine

解决方案


推荐阅读