Тестване на AngularJS 2 модул за маршрут, тест за маршрут за навигация при влизане

Пиша модулен тест за тестване на маршрута, имам страница за вход с бутон за вход, искам да тествам, че при щракване върху моя бутон за вход страницата трябва да навигира към страницата на таблото за управление, но не съм сигурен как да го направя.

ето няколко реда код

import {
  provide, DirectiveResolver, ViewResolver
}
from 'angular2/core';
import {
  describe, expect, it, xit, inject, beforeEachProviders, beforeEach, injectAsync, TestComponentBuilder, setBaseTestProviders
}
from 'angular2/testing';
import {
  TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS
}
from 'angular2/platform/testing/browser';

import {
  Router, RouterOutlet, RouterLink, RouteParams, RouteData, Location, ROUTER_PRIMARY_COMPONENT
}
from 'angular2/router';
import {
  RootRouter
}
from 'angular2/src/router/router';
import {
  RouteRegistry
}
from 'angular2/src/router/route_registry';
import {
  SpyLocation
}
from 'angular2/src/mock/location_mock';

import {
  LoginComponent
}
from '../js/login.component';
import {
  EnterpriseSearchComponent
}
from '../js/enterprise-search.component';
import {
  AppConfig
}
from '../js/services/appconfig';

describe('login component', () => {
  var location, router;

  beforeEachProviders(() => {
    return [
      TEST_BROWSER_PLATFORM_PROVIDERS, TEST_BROWSER_APPLICATION_PROVIDERS,
      provide(ROUTER_PRIMARY_COMPONENT, {
        useValue: EnterpriseSearchComponent
      }),
      provide(Router, {
        useClass: RootRouter
      }), RouteRegistry,
      provide(Location, {
        useClass: SpyLocation
      }), AppConfig
    ]
  });

  beforeEach(inject([Router, Location], (r, l) => {
    router = r;
    location = l;
  }));

  it('Should be able to navigate to Login page', (done) => {
    router.navigate(['Login']).then(() => {
      expect(location.path()).toBe('/login');
      done();
    }).catch(e => done.fail(e));
  });

  it('should validate login', injectAsync([TestComponentBuilder], (tcb) => {
    return tcb.createAsync(LoginComponent).then((fixture) => {
      fixture.detectChanges();
      let compiled = fixture.debugElement.nativeElement;
      let instance = fixture.componentInstance;

      compiled.querySelector("#userid").value = 'dummyid';
      compiled.querySelector("#passwrd").value = 'dummypassword';
      fixture.detectChanges();

      compiled = fixture.debugElement.nativeElement;
      instance = fixture.componentInstance;


      compiled.querySelector("#loginbtn").click();
      fixture.detectChanges();


      // here is where i want to test that the page is navigated to dashboard screen


    });
  }));

});

в горния примерен код, в последната тестова спецификация, искам да тествам навигацията


person Prakash    schedule 14.04.2016    source източник


Отговори (1)


const element = fixture.nativeElement;
                fixture.detectChanges();
                expect(element.querySelectorAll('.dashboard-title')).toBe('Dashboard');

или по-чист начин според мен е да

първо поставете устройството си в поле, т.е

 return tcb.createAsync(LoginComponent).then((fixture) => {
            this.myFixture = fixture;
...

След това можете да го валидирате в различен „случай“, че ако тази страница съдържа конкретен елемент, който има само страницата на таблото ви за управление

it('is this the login page?', () => {
            const element = this.myFixture.nativeElement;
            this.myFixture.detectChanges();
            expect(element.querySelectorAll('.dashboard-title')).toBe('Dashboard');
        });
person eko    schedule 14.04.2016
comment
Нямам такова заглавие на страницата, но целта ми е да го тествам с помощта на URI, като - localhost:3000/dashboard, би трябвало да мога да получа location.path() като „табло за управление“ - person Prakash; 14.04.2016
comment
Използвам phantomjs, за да изпълня моя единичен тестов случай, получавам следния изход, когато използвам 'window.location.pathname': /context.html. И когато използвам „browser().location().url()“, получавам грешка браузърът е недефиниран, тъй като трябва да го импортирам от някаква библиотека. - person Prakash; 14.04.2016