简体   繁体   中英

RouteLink testing angular2

I am testing a Component that use the RouteLink directive like this way :

let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let el: DebugElement;
let injector: Injector;
let languageService: TranslateService;
let location: Location;
let backend: MockBackend;
let connection: MockConnection; // this will be set when a new connection is  emitted from the backend.

let mockRouter: any;
let mockActivatedRoute: any;
const mockBackendResponse = (connection: MockConnection, response: string) => {
  connection.mockRespond(new Response(new ResponseOptions({ body: response })));
};
describe('testComponent', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AppComponent],
      imports: [HttpModule, RouterTestingModule, TranslateModule.forRoot({
        provide: TranslateLoader,
        useFactory: (http: Http) => new TranslateStaticLoader(http, './assets/language', '.json'),
        deps: [Http]
      })],
      providers: [
        { provide: LanguageService, useClass: LanguageService },
        { provide: BackendLocatorService, useClass: BackendLocatorService },
        { provide: XHRBackend, useClass: MockBackend },
        { provide: APP_BASE_HREF, useValue: '/' }
      ]
    });

    injector = getTestBed();
    backend = injector.get(XHRBackend);
    languageService = injector.get(TranslateService);
    location = injector.get(Location);

    backend.connections.subscribe((c: MockConnection) => connection = c);
    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.componentInstance; // BannerComponent test instance
    // get title DebugElement by element name
  });
  it('is defined', () => {
    expect(TranslateService).toBeDefined();
    expect(languageService).toBeDefined();
    expect(languageService instanceof TranslateService).toBeTruthy();
  });

  it('ROUTLINK CLICK', () => {
    fixture.detectChanges();
    let links = fixture.nativeElement.querySelectorAll('a');
    links[1].click();
    console.log(links[0]);
    expect(location.path()).toBe('/home');
  });
});

I try to get the <a> tag and click on it in order to get the current path but the problem is that the current path is always '' , nothing :( here is the error :

 Chrome 53.0.2785 (Windows 7 0.0.0) testComponent ROUTLINK CLICK FAILED
 Expected '' to be '/home'.

Any idea ?

So you have a current error, and after you fix that, you will get another error.

The current error Expected '' to be '/home' is because the click() on the anchor involves asynchronous event handling. But your expectation is synchronous and happens right after the click() , before the asynchronous operation completes.

To fix this you can make the test async , and then after the click() , you can wait for asynchronous operations by calling fixture.whenStable()

import { async } from '@angular/core/testing';

                  // use async
it('ROUTLINK CLICK', async(() => {
  fixture.detectChanges();
  let links = fixture.nativeElement.querySelectorAll('a');
  links[1].click();
  fixture.whenStable().then(() => {
    expect(location.path()).toBe('/home');
  });
}));

Once you fix this, you will run into another problem. Currently you have no routes configured for the RouterTestingModule . Set it up by calling RouterTestingModule.withRoutes(Routes) . You can use your real application routes or if you want, set up some fake routes for testing. See example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM