Модульное тестирование маршрута 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