Angular 2 Jasmine无法绑定到'routerLink',因为它不是'a'的已知属性

Bhe*_*zie 26 unit-testing jasmine angular-routing angular

我正在为我的Navbar组件创建一个单元测试,我收到一个错误:

无法绑定到'routerLink',因为它不是'a'的已知属性

Navbar组件TS

import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { NavActiveService } from '../../../services/navactive.service';
import { GlobalEventsManager } from '../../../services/GlobalEventsManager';

@Component({
  moduleId: module.id,
  selector: 'my-navbar',
  templateUrl: 'navbar.component.html',
  styleUrls:['navbar.component.css'],
  providers: [NavActiveService]
})
export class NavComponent {
  showNavBar: boolean = true;

  constructor(private router: Router,
              private navactiveservice:NavActiveService,
              private globalEventsManager: GlobalEventsManager){

    this.globalEventsManager.showNavBar.subscribe((mode:boolean)=>{
      this.showNavBar = mode;
    });

  }

}
Run Code Online (Sandbox Code Playgroud)

导航组件规格

import { ComponentFixture, TestBed, async } from '@angular/core/testing';    
import { NavComponent } from './navbar.component';
import { DebugElement }    from '@angular/core';
import { By }              from '@angular/platform-browser';
import { Router } from '@angular/router';

export function main() {
    describe('Navbar component', () => {

        let de: DebugElement;
        let comp: NavComponent;
        let fixture: ComponentFixture<NavComponent>;
        let router: Router;

        // preparing module for testing
        beforeEach(async(() => {
            TestBed.configureTestingModule({
                declarations: [NavComponent],
            }).compileComponents().then(() => {

                fixture = TestBed.createComponent(NavComponent);
                comp = fixture.componentInstance;
                de = fixture.debugElement.query(By.css('p'));

            });
        }));


        it('should create component', () => expect(comp).toBeDefined());


/*        it('should have expected <p> text', () => {
            fixture.detectChanges();
            const h1 = de.nativeElement;
            expect(h1.innerText).toMatch(" ");
        });*/


    });
}
Run Code Online (Sandbox Code Playgroud)

我意识到我需要添加路由器作为间谍,但如果我将其添加为SpyObj并将其声明为提供者,我会得到相同的错误.

有没有更好的方法来添加修复此错误?

编辑:工作单位测试

根据答案构建此单元测试:

import { ComponentFixture, TestBed, async  } from '@angular/core/testing';
import { NavComponent } from './navbar.component';
import { DebugElement }    from '@angular/core';
import { By }              from '@angular/platform-browser';
import { RouterLinkStubDirective, RouterOutletStubComponent } from '../../../../test/router-stubs';
import { Router } from '@angular/router';
import { GlobalEventsManager } from '../../../services/GlobalEventsManager';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../shared.module';


export function main() {
    let comp: NavComponent;
    let fixture: ComponentFixture<NavComponent>;
    let mockRouter:any;
    class MockRouter {
        //noinspection TypeScriptUnresolvedFunction
        navigate = jasmine.createSpy('navigate');
    }

    describe('Navbar Componenet', () => {

        beforeEach( async(() => {
            mockRouter = new MockRouter();
            TestBed.configureTestingModule({
                imports: [ SharedModule ]
            })

            // Get rid of app's Router configuration otherwise many failures.
            // Doing so removes Router declarations; add the Router stubs
                .overrideModule(SharedModule, {
                    remove: {
                        imports: [ RouterModule ],

                    },
                    add: {
                        declarations: [ RouterLinkStubDirective, RouterOutletStubComponent ],
                        providers: [ { provide: Router, useValue: mockRouter }, GlobalEventsManager ],
                    }
                })

                .compileComponents()

                .then(() => {
                    fixture = TestBed.createComponent(NavComponent);
                    comp    = fixture.componentInstance;
                });
        }));

        tests();
    });


        function tests() {
            let links: RouterLinkStubDirective[];
            let linkDes: DebugElement[];

            beforeEach(() => {
                // trigger initial data binding
                fixture.detectChanges();

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

                // get the attached link directive instances using the DebugElement injectors
                links = linkDes
                    .map(de => de.injector.get(RouterLinkStubDirective) as RouterLinkStubDirective);
            });

            it('can instantiate it', () => {
                expect(comp).not.toBeNull();
            });

            it('can get RouterLinks from template', () => {
                expect(links.length).toBe(5, 'should have 5 links');
                expect(links[0].linkParams).toBe( '/', '1st link should go to Home');
                expect(links[1].linkParams).toBe('/', '2nd link should go to Home');
expect(links[2].linkParams).toBe('/upload', '3rd link should go to Upload');
                expect(links[3].linkParams).toBe('/about', '4th link should to to About');
                expect(links[4].linkParams).toBe('/login', '5th link should go to Logout');
            });

            it('can click Home link in template', () => {
                const uploadLinkDe = linkDes[1];
                const uploadLink = links[1];

                expect(uploadLink.navigatedTo).toBeNull('link should not have navigated yet');

                uploadLinkDe.triggerEventHandler('click', null);
                fixture.detectChanges();

                expect(uploadLink.navigatedTo).toBe('/');
            });


            it('can click upload link in template', () => {
                const uploadLinkDe = linkDes[2];
                const uploadLink = links[2];

                expect(uploadLink.navigatedTo).toBeNull('link should not have navigated yet');

                uploadLinkDe.triggerEventHandler('click', null);
                fixture.detectChanges();

                expect(uploadLink.navigatedTo).toBe('/upload');
            });

            it('can click about link in template', () => {
                const uploadLinkDe = linkDes[3];
                const uploadLink = links[3];

                expect(uploadLink.navigatedTo).toBeNull('link should not have navigated yet');

                uploadLinkDe.triggerEventHandler('click', null);
                fixture.detectChanges();

                expect(uploadLink.navigatedTo).toBe('/about');
            });

            it('can click logout link in template', () => {
                const uploadLinkDe = linkDes[4];
                const uploadLink = links[4];

                expect(uploadLink.navigatedTo).toBeNull('link should not have navigated yet');

                uploadLinkDe.triggerEventHandler('click', null);
                fixture.detectChanges();

                expect(uploadLink.navigatedTo).toBe('/login');
            });
        }
}
Run Code Online (Sandbox Code Playgroud)

Adr*_*rma 33

只需添加以下行:

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


TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  declarations: [ ComponentHeaderComponent ]
})
Run Code Online (Sandbox Code Playgroud)

TestBed.configureTestingModule您的组件spec.ts文件

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


TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  declarations: [ ComponentHeaderComponent ]
})
Run Code Online (Sandbox Code Playgroud)

喜欢:

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


TestBed.configureTestingModule({
  imports: [RouterTestingModule],
  declarations: [ ComponentHeaderComponent ]
})
Run Code Online (Sandbox Code Playgroud)

  • 无意冒犯,但我认为这应该是公认的答案 (2认同)

小智 19

所述NG2测试文档通过使用RouterLinkStubDirective和RouterOutletStubComponent使得routerLink解决这个的<一>的已知属性.基本上它说使用RouterOutletStubComponent是一种测试routerLinks的安全方法,没有使用真正的RouterOutlet的所有复杂性和错误.您的项目需要知道它存在,因此它不会抛出错误,但在这种情况下它不需要实际执行任何操作.通过RouterLinkStubDirective,您可以单击<a>与routerLink指令的链接,并获取足够的信息来测试它是否被点击(navigatedTo)并转到正确的路由(linkParams).除此之外的任何功能,你真的不再孤立地测试你的组件.

在app/app.component.spec.ts中查看他们的演示.抓住测试/ router-stubs.ts并添加到您的项目中.然后,您将2个存根项注入TestBed声明.

  • 404演示链接:-( (29认同)