Angular 5和Mocha单元测试 - 间谍组件方法 - 无法匹配任何路由。网址细分:'/'

时间:2018-04-12 15:48:37

标签: angular unit-testing mocha sinon

我的应用程序中有一个简单的导航组件,它需要一个“navItems”数组(每个项目都是一个具有路由,标签等属性的对象 - [{route: '/', label: 'navigation.home'}]

这是组件HTML

<nav>
  <mat-nav-list>
    <div *ngFor="let navItem of navList">     
      <a mat-button
         [routerLink]="[navItem.url]"
         (click)="doSomething()"
         routerLinkActive="active">
        {{navItem.label | translate}}
      </a>       
    </div>
  </mat-nav-list>
</nav>

在我的组件中,我有以下

export class NavigationComponent {

  public navList: navItems[] = [{url: '/my-url', label: 'home.page'}, {}, {}]; // naturally I have simplified this

  public doSomething() {
    console.log('doSomething');
  }
}

现在我想确保在点击链接或“a”标记时调用doSomething方法。因此,在我的spec文件中,我有以下内容(请注意,由于某些原因,这个项目使用的是Mocha而不是Jasmin) - 我再次尝试在此处减少代码以提高清晰度

beforeEach(() => {
// Allows overriding default providers, directives, pipes
    TestBed.configureTestingModule({
      imports: [
        MaterialModule,
        TranslateTestingModule.forRoot(),
        AuthTestingModule.forRoot(),
        RouterTestingModule.withRoutes([])
      ],
      declarations: [
        NavigationComponent
      ],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ]
    });
});

beforeEach(() => {
    fixture = TestBed.createComponent(NavigationComponent);
    component = fixture.componentInstance;
    element = fixture.nativeElement;
  });

describe('...', () => {

 it('should call the doSomething() method ', () => {

    const spyDoSomething = sinon.stub(component, 'doSomething' as any);
    fixture.debugElement.nativeElement.querySelector('a').click();

    expect(spyDoSomething.calledOnce).to.be.eq(true);
  });   
});

我认为这会有效,但我收到以下错误:

  

'未处理承诺拒绝:','无法匹配任何路线。网址细分:   'scbas'',';区域:','有角',';任务:','Promise.then',';值:',   错误{},'错误:无法匹配任何路由。网址细分:'/ my-url'

我是否需要阻止实际点击触发Angular路由器?

任何建议都将受到赞赏。

1 个答案:

答案 0 :(得分:0)

在这种情况下,您实际上并不需要提供实际可以通过提供商获得的RouterTestingModule。这是Zip

主要区别在于我用RouterTestingModule取代了 { provide: Router, useValue: { navigate: jasmine.createSpy('navigate') } }