2

我正在测试一个使用 RouteLink 指令的组件,如下所示:

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');
  });
});

我尝试获取<a>标签并单击它以获取当前路径,但问题是当前路径始终为 '' ,什么都没有 :( 这是错误:

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

任何想法 ?

4

1 回答 1

3

所以你有一个当前错误,在你修复它之后,你会得到另一个错误。

当前的错误Expected '' to be '/home'是因为click()锚点上的涉及异步事件处理。但是您的期望是同步的,并且click()在异步操作完成之前发生在 , 之后。

要解决此问题,您可以进行测试async,然后在 之后click(),您可以通过调用等待异步操作 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');
  });
}));

一旦你解决了这个问题,你会遇到另一个问题。目前您没有为RouterTestingModule. 通过调用设置它RouterTestingModule.withRoutes(Routes)。您可以使用真实的应用程序路由,或者如果您愿意,可以设置一些假路由进行测试。见例子

于 2016-09-21T13:32:56.583 回答