Browse Source

test: fix tests

pull/1834/head
mehmet-erim 7 years ago
parent
commit
178db0fa86
  1. 57
      npm/ng-packs/packages/core/src/lib/tests/dynamic-layout.component.spec.ts
  2. 2
      npm/ng-packs/packages/core/src/lib/tests/router-outlet.component.spec.ts
  3. 18
      npm/ng-packs/packages/core/tsconfig.spec.json
  4. 17
      npm/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts
  5. 9
      npm/ng-packs/packages/theme-shared/src/lib/tests/button.component.spec.ts
  6. 83
      npm/ng-packs/packages/theme-shared/src/lib/tests/error.handler.spec.ts
  7. 46
      npm/ng-packs/packages/theme-shared/src/lib/tests/state-overwrite.ts

57
npm/ng-packs/packages/core/src/lib/tests/dynamic-layout.component.spec.ts

@ -1,17 +1,19 @@
import { ConfigState, CoreModule, DynamicLayoutComponent, eLayoutType, ABP, RouterOutletComponent } from '@abp/ng.core';
import { Location } from '@angular/common';
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { createRoutingFactory, SpectatorRouting, SpyObject } from '@ngneat/spectator'; import { createRoutingFactory, SpectatorRouting, SpyObject } from '@ngneat/spectator';
import { NgxsModule, Store } from '@ngxs/store'; import { NgxsModule, Store } from '@ngxs/store';
import { LAYOUTS, ThemeBasicModule } from '../../../../theme-basic/src/public-api';
import { OAuthService } from 'angular-oauth2-oidc'; import { OAuthService } from 'angular-oauth2-oidc';
import { NgxsResetPluginModule, StateOverwrite } from 'ngxs-reset-plugin'; import { NgxsResetPluginModule, StateOverwrite } from 'ngxs-reset-plugin';
import { LAYOUTS, ThemeBasicModule } from '../../../../theme-basic/src/public-api';
import { eLayoutType } from '../enums';
import { ABP } from '../models';
import { RouterOutletComponent, CoreModule, DynamicLayoutComponent, ConfigState } from '@abp/ng.core';
import { ThemeSharedModule } from '../../../../theme-shared/src/public-api'; import { ThemeSharedModule } from '../../../../theme-shared/src/public-api';
import { ActivatedRoute } from '@angular/router'; import { MessageService } from 'primeng/components/common/messageservice';
@Component({ @Component({
selector: 'abp-dummy', selector: 'abp-dummy',
template: '{{route.snapshot.data?.name}} works!' template: '{{route.snapshot.data?.name}} works!',
}) })
class DummyComponent { class DummyComponent {
constructor(public route: ActivatedRoute) {} constructor(public route: ActivatedRoute) {}
@ -25,12 +27,13 @@ describe('DynamicLayoutComponent', () => {
CoreModule, CoreModule,
NgxsModule.forRoot([ConfigState]), NgxsModule.forRoot([ConfigState]),
NgxsResetPluginModule.forRoot(), NgxsResetPluginModule.forRoot(),
ThemeSharedModule.forRoot(), ThemeSharedModule,
ThemeBasicModule ThemeBasicModule,
], ],
declarations: [DummyComponent], declarations: [DummyComponent],
entryComponents: [],
stubsEnabled: false, stubsEnabled: false,
providers: [{ provide: OAuthService, useValue: { getAccessToken: () => true } }], providers: [MessageService, { provide: OAuthService, useValue: { getAccessToken: () => true } }],
routes: [ routes: [
{ path: '', component: RouterOutletComponent }, { path: '', component: RouterOutletComponent },
{ {
@ -40,14 +43,14 @@ describe('DynamicLayoutComponent', () => {
{ {
path: 'childWithoutLayout', path: 'childWithoutLayout',
component: DummyComponent, component: DummyComponent,
data: { name: 'childWithoutLayout' } data: { name: 'childWithoutLayout' },
}, },
{ {
path: 'childWithLayout', path: 'childWithLayout',
component: DummyComponent, component: DummyComponent,
data: { name: 'childWithLayout' } data: { name: 'childWithLayout' },
} },
] ],
}, },
{ {
path: 'withData', path: 'withData',
@ -56,10 +59,10 @@ describe('DynamicLayoutComponent', () => {
{ {
path: '', path: '',
component: DummyComponent, component: DummyComponent,
data: { name: 'withData' } data: { name: 'withData' },
} },
], ],
data: { layout: eLayoutType.empty } data: { layout: eLayoutType.empty },
}, },
{ {
path: 'withoutLayout', path: 'withoutLayout',
@ -68,12 +71,12 @@ describe('DynamicLayoutComponent', () => {
{ {
path: '', path: '',
component: DummyComponent, component: DummyComponent,
data: { name: 'withoutLayout' } data: { name: 'withoutLayout' },
} },
], ],
data: { layout: null } data: { layout: null },
} },
] ],
}); });
let spectator: SpectatorRouting<RouterOutletComponent>; let spectator: SpectatorRouting<RouterOutletComponent>;
@ -95,16 +98,16 @@ describe('DynamicLayoutComponent', () => {
{ {
path: 'parentWithLayout', path: 'parentWithLayout',
layout: eLayoutType.application, layout: eLayoutType.application,
children: [{ path: 'childWithoutLayout' }, { path: 'childWithLayout', layout: eLayoutType.account }] children: [{ path: 'childWithoutLayout' }, { path: 'childWithLayout', layout: eLayoutType.account }],
} },
] ],
}, },
{ path: 'withData', layout: eLayoutType.application }, { path: 'withData', layout: eLayoutType.application },
, ,
] as ABP.FullRoute[], ] as ABP.FullRoute[],
environment: { application: {} } environment: { application: {} },
} },
]) ]),
); );
}); });
@ -139,7 +142,7 @@ describe('DynamicLayoutComponent', () => {
it('should not display any layout when layouts are empty', async () => { it('should not display any layout when layouts are empty', async () => {
store.dispatch( store.dispatch(
new StateOverwrite([ConfigState, { ...store.selectSnapshot(ConfigState), requirements: { layouts: [] } }]) new StateOverwrite([ConfigState, { ...store.selectSnapshot(ConfigState), requirements: { layouts: [] } }]),
); );
spectator.detectChanges(); spectator.detectChanges();

2
npm/ng-packs/packages/core/src/lib/tests/router-outlet.component.spec.ts

@ -1,6 +1,6 @@
import { Spectator, createComponentFactory, createHostFactory } from '@ngneat/spectator'; import { Spectator, createComponentFactory, createHostFactory } from '@ngneat/spectator';
import { RouterOutletComponent } from '@abp/ng.core';
import { RouterTestingModule } from '@angular/router/testing'; import { RouterTestingModule } from '@angular/router/testing';
import { RouterOutletComponent } from '../components/router-outlet.component';
describe('RouterOutletComponent', () => { describe('RouterOutletComponent', () => {
let spectator: Spectator<RouterOutletComponent>; let spectator: Spectator<RouterOutletComponent>;

18
npm/ng-packs/packages/core/tsconfig.spec.json

@ -2,16 +2,12 @@
"extends": "../../tsconfig.json", "extends": "../../tsconfig.json",
"compilerOptions": { "compilerOptions": {
"outDir": "../../out-tsc/spec", "outDir": "../../out-tsc/spec",
"types": [ "types": ["jasmine", "node"],
"jasmine", "paths": {
"node" "@abp/ng.core": ["packages/core/src/public-api.ts"],
] "@abp/ng.core/*": ["packages/core/src/lib/*"]
}
}, },
"files": [ "files": ["src/test.ts"],
"src/test.ts" "include": ["**/*.spec.ts", "**/*.d.ts"]
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
} }

17
npm/ng-packs/packages/theme-shared/src/lib/handlers/error.handler.ts

@ -6,15 +6,16 @@ import {
EmbeddedViewRef, EmbeddedViewRef,
Injectable, Injectable,
Injector, Injector,
NgZone,
RendererFactory2, RendererFactory2,
} from '@angular/core'; } from '@angular/core';
import { Navigate, RouterState } from '@ngxs/router-plugin'; import { Router } from '@angular/router';
import { Actions, ofActionSuccessful, Store } from '@ngxs/store'; import { Actions, ofActionSuccessful, Store } from '@ngxs/store';
import { Observable } from 'rxjs'; import { Observable } from 'rxjs';
import snq from 'snq';
import { ErrorComponent } from '../components/error/error.component'; import { ErrorComponent } from '../components/error/error.component';
import { Toaster } from '../models/toaster'; import { Toaster } from '../models/toaster';
import { ConfirmationService } from '../services/confirmation.service'; import { ConfirmationService } from '../services/confirmation.service';
import snq from 'snq';
export const DEFAULT_ERROR_MESSAGES = { export const DEFAULT_ERROR_MESSAGES = {
defaultError: { defaultError: {
@ -47,6 +48,8 @@ export const DEFAULT_ERROR_MESSAGES = {
export class ErrorHandler { export class ErrorHandler {
constructor( constructor(
private actions: Actions, private actions: Actions,
private router: Router,
private ngZone: NgZone,
private store: Store, private store: Store,
private confirmationService: ConfirmationService, private confirmationService: ConfirmationService,
private appRef: ApplicationRef, private appRef: ApplicationRef,
@ -125,11 +128,11 @@ export class ErrorHandler {
} }
private navigateToLogin() { private navigateToLogin() {
this.store.dispatch( this.ngZone.run(() => {
new Navigate(['/account/login'], null, { this.router.navigate(['/account/login'], {
state: { redirectUrl: this.store.selectSnapshot(RouterState).state.url }, state: { redirectUrl: this.router.url },
}), });
); });
} }
createErrorComponent(instance: Partial<ErrorComponent>) { createErrorComponent(instance: Partial<ErrorComponent>) {

9
npm/ng-packs/packages/theme-shared/src/lib/tests/button.component.spec.ts

@ -1,11 +1,4 @@
import { CoreModule } from '@abp/ng.core'; import { createHostFactory, SpectatorHost } from '@ngneat/spectator';
import {
createComponentFactory,
createHostFactory,
Spectator,
SpectatorHost,
createTestComponentFactory
} from '@ngneat/spectator';
import { ButtonComponent } from '../components'; import { ButtonComponent } from '../components';
describe('ButtonComponent', () => { describe('ButtonComponent', () => {

83
npm/ng-packs/packages/theme-shared/src/lib/tests/error.handler.spec.ts

@ -3,9 +3,7 @@ import { Location } from '@angular/common';
import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { createRoutingFactory, SpectatorRouting } from '@ngneat/spectator'; import { createRoutingFactory, SpectatorRouting } from '@ngneat/spectator';
import { RouterState } from '@ngxs/router-plugin';
import { NgxsModule, Store } from '@ngxs/store'; import { NgxsModule, Store } from '@ngxs/store';
import { NgxsResetPluginModule, StateOverwrite } from 'ngxs-reset-plugin';
import { DEFAULT_ERROR_MESSAGES, ErrorHandler } from '../handlers'; import { DEFAULT_ERROR_MESSAGES, ErrorHandler } from '../handlers';
import { ThemeSharedModule } from '../theme-shared.module'; import { ThemeSharedModule } from '../theme-shared.module';
@ -14,96 +12,97 @@ class DummyComponent {
constructor(public errorHandler: ErrorHandler, public store: Store) {} constructor(public errorHandler: ErrorHandler, public store: Store) {}
} }
describe('With Custom Host Component', () => { describe('ErrorHandler', () => {
let component: SpectatorRouting<DummyComponent>; let spectator: SpectatorRouting<DummyComponent>;
let store: Store;
const createComponent = createRoutingFactory({ const createComponent = createRoutingFactory({
component: DummyComponent, component: DummyComponent,
imports: [CoreModule, ThemeSharedModule.forRoot(), NgxsModule.forRoot([]), NgxsResetPluginModule.forRoot()], imports: [CoreModule, ThemeSharedModule.forRoot(), NgxsModule.forRoot([])],
stubsEnabled: false, stubsEnabled: false,
routes: [{ path: '', component: DummyComponent }, { path: 'account/login', component: RouterOutletComponent }] routes: [{ path: '', component: DummyComponent }, { path: 'account/login', component: RouterOutletComponent }],
}); });
beforeEach(() => { beforeEach(() => {
component = createComponent(); spectator = createComponent();
store = spectator.component.store;
const abpError = document.querySelector('abp-error'); const abpError = document.querySelector('abp-error');
if (abpError) document.body.removeChild(abpError); if (abpError) document.body.removeChild(abpError);
}); });
it('should display the error component when server error occurs', () => { it('should display the error component when server error occurs', () => {
component.component.store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 500 }))); store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 500 })));
component.detectChanges(); spectator.detectChanges();
expect(document.querySelector('.error-template')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError500.title); expect(document.querySelector('.error-template')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError500.title);
expect(document.querySelector('.error-details')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError500.details); expect(document.querySelector('.error-details')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError500.details);
}); });
it('should display the error component when authorize error occurs', () => { it('should display the error component when authorize error occurs', () => {
component.component.store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 403 }))); store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 403 })));
component.detectChanges(); spectator.detectChanges();
expect(document.querySelector('.error-template')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError403.title); expect(document.querySelector('.error-template')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError403.title);
expect(document.querySelector('.error-details')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError403.details); expect(document.querySelector('.error-details')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError403.details);
}); });
it('should display the error component when unknown error occurs', () => { it('should display the error component when unknown error occurs', () => {
component.component.store.dispatch( store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 0, statusText: 'Unknown Error' })));
new RestOccurError(new HttpErrorResponse({ status: 0, statusText: 'Unknown Error' })) spectator.detectChanges();
);
component.detectChanges();
expect(document.querySelector('.error-template')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultErrorUnknown.title); expect(document.querySelector('.error-template')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultErrorUnknown.title);
expect(document.querySelector('.error-details')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultErrorUnknown.details); expect(document.querySelector('.error-details')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultErrorUnknown.details);
}); });
it('should display the confirmation when not found error occurs', () => { it('should display the confirmation when not found error occurs', () => {
component.component.store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 404 }))); store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 404 })));
component.detectChanges(); spectator.detectChanges();
expect(component.query('.abp-confirm-summary')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError404.title); expect(spectator.query('.abp-confirm-summary')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError404.title);
expect(component.query('.abp-confirm-body')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError404.details); expect(spectator.query('.abp-confirm-body')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError404.details);
}); });
it('should display the confirmation when default error occurs', () => { it('should display the confirmation when default error occurs', () => {
component.component.store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 412 }))); store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 412 })));
component.detectChanges(); spectator.detectChanges();
expect(component.query('.abp-confirm-summary')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError.title); expect(spectator.query('.abp-confirm-summary')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError.title);
expect(component.query('.abp-confirm-body')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError.details); expect(spectator.query('.abp-confirm-body')).toHaveText(DEFAULT_ERROR_MESSAGES.defaultError.details);
}); });
it('should display the confirmation when authenticated error occurs', async () => { it('should display the confirmation when authenticated error occurs', async () => {
component.component.store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 401 }))); store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 401 })));
component.detectChanges(); spectator.detectChanges();
component.component.store.dispatch(new StateOverwrite([RouterState, { state: { url: '/' } }])); spectator.click('#confirm');
component.click('#confirm'); await spectator.fixture.whenStable();
await component.fixture.whenStable(); expect(spectator.get(Location).path()).toBe('/account/login');
expect(component.get(Location).path()).toBe('/account/login');
}); });
it('should display the confirmation when authenticated error occurs with _AbpErrorFormat header', async () => { it('should display the confirmation when authenticated error occurs with _AbpErrorFormat header', async () => {
let headers: HttpHeaders = new HttpHeaders(); let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('_AbpErrorFormat', '_AbpErrorFormat'); headers = headers.append('_AbpErrorFormat', '_AbpErrorFormat');
component.component.store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 401, headers }))); store.dispatch(new RestOccurError(new HttpErrorResponse({ status: 401, headers })));
component.detectChanges(); spectator.detectChanges();
component.component.store.dispatch(new StateOverwrite([RouterState, { state: { url: '/' } }]));
component.click('#confirm'); spectator.click('#confirm');
await component.fixture.whenStable(); await spectator.fixture.whenStable();
expect(component.get(Location).path()).toBe('/account/login'); expect(spectator.get(Location).path()).toBe('/account/login');
}); });
it('should display the confirmation when error occurs with _AbpErrorFormat header', () => { it('should display the confirmation when error occurs with _AbpErrorFormat header', () => {
let headers: HttpHeaders = new HttpHeaders(); let headers: HttpHeaders = new HttpHeaders();
headers = headers.append('_AbpErrorFormat', '_AbpErrorFormat'); headers = headers.append('_AbpErrorFormat', '_AbpErrorFormat');
component.component.store.dispatch( store.dispatch(
new RestOccurError( new RestOccurError(
new HttpErrorResponse({ new HttpErrorResponse({
error: { error: { message: 'test message', details: 'test detail' } }, error: { error: { message: 'test message', details: 'test detail' } },
status: 412, status: 412,
headers headers,
}) }),
) ),
); );
component.detectChanges(); spectator.detectChanges();
expect(component.query('.abp-confirm-summary')).toHaveText('test message'); expect(spectator.query('.abp-confirm-summary')).toHaveText('test message');
expect(component.query('.abp-confirm-body')).toHaveText('test detail'); expect(spectator.query('.abp-confirm-body')).toHaveText('test detail');
}); });
}); });

46
npm/ng-packs/packages/theme-shared/src/lib/tests/state-overwrite.ts

@ -0,0 +1,46 @@
import { Inject, Injectable, InjectionToken, Provider } from '@angular/core';
import { getActionTypeFromInstance, InitState, NgxsPlugin, NGXS_PLUGINS, setValue } from '@ngxs/store';
export const NGXS_OVERWRITE_PLUGIN_VALUE = new InjectionToken('NGXS_OVERWRITE_PLUGIN_VALUE');
export class StateOverwrite {
static readonly type = '[StateOverwrite] Patch';
constructor(public payload: { stateName: string; value: any }) {}
}
@Injectable()
export class OverwritePlugin implements NgxsPlugin {
initialized: boolean;
constructor(@Inject(NGXS_OVERWRITE_PLUGIN_VALUE) private options: any) {}
handle(state, action, next) {
const type = getActionTypeFromInstance(action);
if (action instanceof InitState && !this.initialized) {
state = { ...state, ...this.options };
console.log(state);
this.initialized = true;
}
if (action instanceof StateOverwrite) {
state = setValue(state, action.payload.stateName, action.payload.value);
}
return next(state, action);
}
}
export function stateOverwriteProviders(value = {}): Provider[] {
return [
{
provide: NGXS_PLUGINS,
useClass: OverwritePlugin,
multi: true,
},
{
provide: NGXS_OVERWRITE_PLUGIN_VALUE,
useValue: value,
},
];
}
Loading…
Cancel
Save