У меня есть приложение Angular, использующее бэкэнд Express. js. Он имеет адресный путь по умолчанию к странице входа /avior/login
. Мне нужно написать тест E2E для всего приложения, и я только начал писать первую тестовую часть, которая должна распознавать страницу входа и сам вход, а затем проверять, было ли перенаправление успешным. Пока я написал этот подверженный ошибкам код:
import { AppPage } from './app.po';
import { browser, logging, element } from 'protractor';
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '@angular/core/testing';
import {AppComponent} from '../../src/app/app.component'
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: AppPage;
let router: Router;
let location: SpyLocation;
let username: 'Test';
let password: 'testtest';
let usernameInput: element(by.css('#inputUser'));
let passwordInput: element(by.css('#inputPassword'));
let loginButton: element(by.css('#loginSubmit'));
describe('Avior App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should navigate to "/avior/login" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/avior/login', 'after initialNavigation()');
expectElementOf(DashboardComponent);
}));
it('should display Login message in the header', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Anmeldung');
});
it('there should be username and password login fields', () => {
// how to check?
});
it('login using false credentials should make you stay put and throw an error', () => {
// how to?
});
it('login using Test:testtset (=successful credentials => successful login) should redirect to /avior/dashboard', () => {
// how to?
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
function loginFn() {
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
};
Как исправить этот код?
ОБНОВЛЕНИЕ
Я попытался упростить свой код пока только тесты маршрутизации, и я получаю новые ошибки. Мой новый код выглядит следующим образом:
import { AppPage } from './app.po';
import { browser, logging, element } from 'protractor';
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '@angular/core/testing';
import {AppComponent} from '../../src/app/app.component'
import {Component} from "@angular/core";
import {RouterTestingModule} from "@angular/router/testing";
import {Routes} from "@angular/router";
import {Router} from "@angular/router";
import { AviorComponent } from '../../src/app/avior/avior.component';
import { DashboardComponent } from '../../src/app/avior/dashboard/dashboard.component';
import { ProfileComponent } from '../../src/app/avior/profile/profile.component';
import { SettingsComponent } from '../../src/app/avior/settings/settings.component';
import { LoginComponent } from '../../src/app/avior/login/login.component';
import { PageNotFoundComponent } from '../../src/app/avior/page-not-found/page-not-found.component';
import { InfoComponent } from '../../src/app/avior/info/info.component';
import { UsersComponent } from '../../src/app/avior/users/users.component';
import { MandatorsComponent } from '../../src/app/avior/mandators/mandators.component';
import { SystemComponent } from '../../src/app/avior/system/system.component';
import { WorkflowsComponent } from '../../src/app/avior/workflows/workflows.component';
import { MessagesComponent } from '../../src/app/avior/messages/messages.component';
import { BrowserDynamicTestingModule,
platformBrowserDynamicTesting } from '@angular/platform-browser-dynamic/testing';
/* let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: AppPage;
let router: Router;
let location: SpyLocation;
let username: 'Chad';
let password: 'chadchad';
let usernameInput: element(by.css('#inputUser'));
let passwordInput: element(by.css('#inputPassword'));
let loginButton: element(by.css('#loginSubmit')); */
const aviorRoutes: Routes = [{
path: '', component: AviorComponent,
children: [
{
path: '', component: ProfileComponent
},
{
path: 'dashboard', component: DashboardComponent,
data: {title: 'Dashboard'},
},
{
path: 'login', component: LoginComponent,
data: {title: 'Login'},
},
{
path: 'logout', component: LoginComponent,
data: {title: 'Login'},
},
{
path: 'profile', component: ProfileComponent,
data: {title: 'Profil'},
},
{
path: 'settings', component: SettingsComponent,
data: {title: 'Einstellungen'},
},
{
path: 'info', component: InfoComponent,
data: {title: 'Info'},
},
{
path: 'users', component: UsersComponent,
data: {title: 'Benutzer'},
},
{
path: 'workflows', component: WorkflowsComponent,
data: {title: 'Workflows'},
},
{
path: 'system', component: SystemComponent,
data: {title: 'System'},
},
{
path: 'mandators', component: MandatorsComponent,
data: {title: 'Mandanten'}
},
{
path: 'messages', component: MessagesComponent,
data: {title: 'Nachrichten'}
},
{
path: '404', component: PageNotFoundComponent,
data: {title: 'Page not found'},
}
]
}];
describe('Avior App', () => {
let page: AppPage;
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting())
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(aviorRoutes)],
declarations: [
DashboardComponent,
ProfileComponent,
SettingsComponent,
LoginComponent,
PageNotFoundComponent,
InfoComponent,
UsersComponent,
MandatorsComponent,
SystemComponent,
WorkflowsComponent,
MessagesComponent
]
});
page = new AppPage();
this.router = TestBed.get(Router);
location = TestBed.get(Location);
this.fixture = TestBed.createComponent(AppComponent);
this.router.initialNavigation();
});
/* it('should navigate to "/avior/login" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/avior/login', 'after initialNavigation()');
expectElementOf(DashboardComponent);
})); */
it('navigate to "" redirects you to /avior/login', fakeAsync(() => {
this.router.navigate(['']);
tick();
expect(location.path()).toBe('/avior/login');
}));
it('navigate to "dashboard" takes you to /dashboard', fakeAsync(() => {
this.router.navigate(['dashboard']);
tick();
expect(location.path()).toBe('avior/dashboard');
}));
it('should display Anmeldung message in the header', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Anmeldung');
});
it('there should be username and password login fields', () => {
});
it('login using false credentials should make you stay put and throw an error', () => {
});
it('login using Chad:chadchad should redirect to /avior/dashboard', () => {
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
/* function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
function loginFn(username, password) {
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
};
*/
Ошибки выбрасываются во время ng e2e
выполнения: - Failed: Can't resolve all parameters for ApplicationModule: (?). - Failed: Cannot read property 'assertPresent' of null