Angular 2 Jasmine Can't bind to 'routerLink' since it isn't a known property of 'a'

孤人 提交于 2019-12-01 02:42:22
Nicole Sands

The Angular Testing docs address this by using RouterLinkDirectiveStub and RouterOutletStubComponent so that routerLink is a known property of <a>.

Basically it says that using RouterOutletStubComponent is a safe way to test routerLinks without all the complications and errors of using the real RouterOutlet. Your project needs to know it exists so it doesn't throw errors but it doesn't need to actually do anything in this case.

The RouterLinkDirectiveStub enables you to click on <a> links with routerLink directive and get just enough information to test that it is being clicked (navigatedTo) and going to the correct route (linkParams). Any more functionality than that and you really aren't testing your component in isolation any more.

Take a look at their Tests Demo in app/app.component.spec.ts. Grab the testing/router-link-directive-stub.ts and add to your project. Then you will inject the 2 stubbed items into your TestBed declarations.

Just import RouterTestingModule in TestBed.configureTestingModule of your components spec.ts file

Eg:

import { RouterTestingModule } from '@angular/router/testing';


TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  declarations: [ ComponentHeaderComponent ]
})

If you want only isolated test and DO NOT CARE about template,you can add NO_ERRORS_SCHEMA. This tells Angular not to show error if it encounters any unknown attribute or element in HTML

Eg:

TestBed.configureTestingModule({
  declarations: [ ComponentHeaderComponent ],
  schemas: [ NO_ERRORS_SCHEMA ]
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!