diff --git a/.eslintignore b/.eslintignore index 60c136febd52..8b65ae5e2e97 100644 --- a/.eslintignore +++ b/.eslintignore @@ -16,11 +16,6 @@ src/main/generated/ src/main/java/ src/main/jib/ src/main/resources/ -src/test/ -src/test/javascript/e2e/ -src/test/javascript/protractor.conf.js -src/test/javascript/jest.conf.js -src/test/k6/ uploads/ webpack/ target/ diff --git a/.eslintrc.json b/.eslintrc.json index e1d6c85cfcb9..029a4b7f7b40 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -1,11 +1,10 @@ { "plugins": [ "@typescript-eslint", - "@typescript-eslint/tslint" + "@typescript-eslint/tslint", + "chai-friendly" ], "extends": [ -// "plugin:@typescript-eslint/eslint-recommended", -// "plugin:@typescript-eslint/recommended", "prettier/@typescript-eslint", "plugin:prettier/recommended" ], @@ -22,7 +21,10 @@ "@typescript-eslint/tslint/config": [ "error", { - "lintFile": "./tslint.json" + "lintFile": "./tslint.json", + "rules": { + "no-unused-expressions": "off" + } } ], "@typescript-eslint/no-unused-vars": [ @@ -33,6 +35,13 @@ "ignoreRestSiblings": false } ], - "@typescript-eslint/no-non-null-assertion": "off" - } + "@typescript-eslint/no-non-null-assertion": "off", + "chai-friendly/no-unused-expressions": 2 + }, + "overrides": [{ + "files": ["mock-*.ts"], + "rules": { + "@typescript-eslint/no-unused-vars": "off" + } + }] } diff --git a/package.json b/package.json index ff267374bc52..109128cf9153 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "compare-versions": "3.6.0", "core-js": "3.6.5", "dompurify": "2.0.10", + "eslint-plugin-chai-friendly": "0.5.0", "export-to-csv": "0.2.1", "franc-min": "5.0.0", "interactjs": "1.9.10", @@ -77,6 +78,7 @@ "sugar": "2.0.6", "ts-jest": "25.4.0", "tslib": "1.11.1", + "tslint-no-unused-expression-chai": "0.1.4", "webstomp-client": "1.2.6", "yarn": "1.22.4", "zone.js": "0.10.3" @@ -176,8 +178,8 @@ "src/{main,test}/java/**/*.java": "bash ./linting.sh" }, "scripts": { - "prettier:format": "prettier --write 'src/{main/webapp,test}/**/*.{json,ts,css,scss,html}'", - "prettier:check": "prettier --check 'src/{main/webapp,test}/**/*.{json,ts,css,scss,html}'", + "prettier:format": "prettier --write 'src/{main/webapp,test}/**/*.{json,ts,js,css,scss,html}'", + "prettier:check": "prettier --check 'src/{main/webapp,test}/**/*.{json,ts,js,css,scss,html}'", "lint": "eslint . --ext .ts", "lint:fix": "yarn run lint --fix", "lint:doc": "tslint --config tslint-doc.json --project tsconfig.json -e 'node_modules/**'", diff --git a/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts b/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts index 08f8f0196c0b..603e6f3e5037 100644 --- a/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts +++ b/src/main/webapp/app/account/password-reset/finish/password-reset-finish.component.ts @@ -29,8 +29,9 @@ export class PasswordResetFinishComponent implements OnInit, AfterViewInit { } ngAfterViewInit() { - if (this.elementRef.nativeElement.querySelector('#password') != null) { - this.renderer.selectRootElement('#password', true).focus(); + const passwordElement = this.elementRef.nativeElement.querySelector('#password'); + if (passwordElement != null) { + this.renderer.selectRootElement(passwordElement, true).focus(); } } diff --git a/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts b/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts index 14aa092e297f..7279574019ff 100644 --- a/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts +++ b/src/main/webapp/app/account/password-reset/init/password-reset-init.component.ts @@ -19,7 +19,10 @@ export class PasswordResetInitComponent implements OnInit, AfterViewInit { } ngAfterViewInit() { - this.renderer.selectRootElement('#email', true).focus(); + const emailElement = this.elementRef.nativeElement.querySelector('#email'); + if (emailElement != null) { + this.renderer.selectRootElement(emailElement, true).focus(); + } } requestReset() { diff --git a/src/main/webapp/app/admin/notification-management/notification-management-update.component.ts b/src/main/webapp/app/admin/notification-management/notification-management-update.component.ts index 5700a9da5166..9b178093915a 100644 --- a/src/main/webapp/app/admin/notification-management/notification-management-update.component.ts +++ b/src/main/webapp/app/admin/notification-management/notification-management-update.component.ts @@ -43,18 +43,18 @@ export class NotificationMgmtUpdateComponent implements OnInit { this.isSaving = true; if (this.notification.id) { this.systemNotificationService.update(this.notification).subscribe( - (response) => this.onSaveSuccess(response.body!), + () => this.onSaveSuccess(), () => this.onSaveError(), ); } else { this.systemNotificationService.create(this.notification).subscribe( - (response) => this.onSaveSuccess(response.body!), + () => this.onSaveSuccess(), () => this.onSaveError(), ); } } - private onSaveSuccess(result: SystemNotification) { + private onSaveSuccess() { this.isSaving = false; this.previousState(); } diff --git a/src/main/webapp/app/admin/notification-management/notification-management.route.ts b/src/main/webapp/app/admin/notification-management/notification-management.route.ts index 62055cf5602d..b3af8667feea 100644 --- a/src/main/webapp/app/admin/notification-management/notification-management.route.ts +++ b/src/main/webapp/app/admin/notification-management/notification-management.route.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { ActivatedRouteSnapshot, Resolve, Route, RouterStateSnapshot } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, Route } from '@angular/router'; import { JhiResolvePagingParams } from 'ng-jhipster'; import { NotificationMgmtUpdateComponent } from 'app/admin/notification-management/notification-management-update.component'; import { SystemNotification } from 'app/entities/system-notification.model'; @@ -14,9 +14,8 @@ export class NotificationMgmtResolve implements Resolve { /** * Resolves the route and initializes system notification from id route param * @param route - * @param state */ - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + resolve(route: ActivatedRouteSnapshot) { const id = route.params['id'] ? route.params['id'] : null; if (id) { return this.service.find(parseInt(id, 10)); diff --git a/src/main/webapp/app/admin/user-management/user-management-update.component.ts b/src/main/webapp/app/admin/user-management/user-management-update.component.ts index 3d579ab301e9..938984e1f7a0 100644 --- a/src/main/webapp/app/admin/user-management/user-management-update.component.ts +++ b/src/main/webapp/app/admin/user-management/user-management-update.component.ts @@ -51,12 +51,12 @@ export class UserManagementUpdateComponent implements OnInit { this.isSaving = true; if (this.user.id !== null) { this.userService.update(this.user).subscribe( - (response) => this.onSaveSuccess(response.body!), + () => this.onSaveSuccess(), () => this.onSaveError(), ); } else { this.userService.create(this.user).subscribe( - (response) => this.onSaveSuccess(response.body!), + () => this.onSaveSuccess(), () => this.onSaveError(), ); } @@ -66,7 +66,7 @@ export class UserManagementUpdateComponent implements OnInit { * Set isSaving to false and navigate to previous page * @param result */ - private onSaveSuccess(result: User) { + private onSaveSuccess() { this.isSaving = false; this.previousState(); } diff --git a/src/main/webapp/app/admin/user-management/user-management.route.ts b/src/main/webapp/app/admin/user-management/user-management.route.ts index a84cb7f5bf3e..d1c410bff4cf 100644 --- a/src/main/webapp/app/admin/user-management/user-management.route.ts +++ b/src/main/webapp/app/admin/user-management/user-management.route.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { ActivatedRouteSnapshot, Resolve, Route, RouterStateSnapshot } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, Route } from '@angular/router'; import { JhiResolvePagingParams } from 'ng-jhipster'; import { User } from 'app/core/user/user.model'; import { UserService } from 'app/core/user/user.service'; @@ -14,9 +14,8 @@ export class UserMgmtResolve implements Resolve { /** * Resolve route to find the user before the route is activated * @param route contains the information about a route associated with a component loaded in an outlet at a particular moment in time - * @param state represents the state of the router at a moment in time */ - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + resolve(route: ActivatedRouteSnapshot) { const login = route.params['login'] ? route.params['login'] : null; if (login) { return this.userService.find(login); diff --git a/src/main/webapp/app/app.main.ts b/src/main/webapp/app/app.main.ts index 538009f7e60a..16cc06ac5908 100644 --- a/src/main/webapp/app/app.main.ts +++ b/src/main/webapp/app/app.main.ts @@ -14,5 +14,5 @@ if (module['hot']) { platformBrowserDynamic() .bootstrapModule(ArtemisAppModule, { preserveWhitespaces: true }) - .then((platformRef) => {}) + .then(() => {}) .catch((err) => console.error(err)); diff --git a/src/main/webapp/app/assessment/assessment-warning/assessment-warning.component.ts b/src/main/webapp/app/assessment/assessment-warning/assessment-warning.component.ts index 3039b000f4ba..1ac13ecb339d 100644 --- a/src/main/webapp/app/assessment/assessment-warning/assessment-warning.component.ts +++ b/src/main/webapp/app/assessment/assessment-warning/assessment-warning.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; +import { Component, Input, OnChanges } from '@angular/core'; import * as moment from 'moment'; import { Exercise } from 'app/entities/exercise.model'; @@ -22,7 +22,7 @@ export class AssessmentWarningComponent implements OnChanges { currentDate: moment.MomentInput; isBeforeDueDate = false; - ngOnChanges(changes: SimpleChanges): void { + ngOnChanges(): void { const dueDate = this.exercise.dueDate; if (dueDate != null) { this.isBeforeDueDate = dueDate.isAfter(this.currentDate); diff --git a/src/main/webapp/app/complaints/complaints-for-tutor/complaints-for-tutor.component.ts b/src/main/webapp/app/complaints/complaints-for-tutor/complaints-for-tutor.component.ts index 6200ac526387..4398a51c16fa 100644 --- a/src/main/webapp/app/complaints/complaints-for-tutor/complaints-for-tutor.component.ts +++ b/src/main/webapp/app/complaints/complaints-for-tutor/complaints-for-tutor.component.ts @@ -57,6 +57,7 @@ export class ComplaintsForTutorComponent implements OnInit { this.complaintResponseService.create(this.complaintResponse).subscribe( (response) => { this.handled = true; + // eslint-disable-next-line chai-friendly/no-unused-expressions this.complaint.complaintType === ComplaintType.MORE_FEEDBACK ? this.jhiAlertService.success('artemisApp.moreFeedbackResponse.created') : this.jhiAlertService.success('artemisApp.complaintResponse.created'); diff --git a/src/main/webapp/app/complaints/list-of-complaints/list-of-complaints.component.ts b/src/main/webapp/app/complaints/list-of-complaints/list-of-complaints.component.ts index 0b57d7aa8866..b666bccdeed3 100644 --- a/src/main/webapp/app/complaints/list-of-complaints/list-of-complaints.component.ts +++ b/src/main/webapp/app/complaints/list-of-complaints/list-of-complaints.component.ts @@ -115,7 +115,7 @@ export class ListOfComplaintsComponent implements OnInit { modalRef.componentInstance.result = cloneDeep(complaint.result); modalRef.componentInstance.onResultModified.subscribe(() => this.loadComplaints()); modalRef.result.then( - (_) => this.loadComplaints(), + () => this.loadComplaints(), () => {}, ); return; diff --git a/src/main/webapp/app/core/auth/user-route-access-service.ts b/src/main/webapp/app/core/auth/user-route-access-service.ts index 8fdcc2a65086..3c3ad6566ee7 100644 --- a/src/main/webapp/app/core/auth/user-route-access-service.ts +++ b/src/main/webapp/app/core/auth/user-route-access-service.ts @@ -4,7 +4,7 @@ import { LocalStorageService } from 'ngx-webstorage'; import { AccountService } from 'app/core/auth/account.service'; import { StateStorageService } from 'app/core/auth/state-storage.service'; import { OrionVersionValidator } from 'app/shared/orion/outdated-plugin-warning/orion-version-validator.service'; -import { filter, first, switchMap } from 'rxjs/operators'; +import { first, switchMap } from 'rxjs/operators'; import { from, of } from 'rxjs'; @Injectable({ providedIn: 'root' }) diff --git a/src/main/webapp/app/core/config/uib-pagination.config.ts b/src/main/webapp/app/core/config/uib-pagination.config.ts deleted file mode 100644 index f9da52573032..000000000000 --- a/src/main/webapp/app/core/config/uib-pagination.config.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { Injectable } from '@angular/core'; -import { NgbPaginationConfig } from '@ng-bootstrap/ng-bootstrap'; -import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; - -@Injectable({ providedIn: 'root' }) -export class PaginationConfig { - // tslint:disable-next-line: no-unused-variable - constructor(private config: NgbPaginationConfig) { - config.boundaryLinks = true; - config.maxSize = 5; - config.pageSize = ITEMS_PER_PAGE; - config.size = 'sm'; - } -} diff --git a/src/main/webapp/app/core/interceptor/auth-expired.interceptor.ts b/src/main/webapp/app/core/interceptor/auth-expired.interceptor.ts index 399e3406563b..f9a5c38b491c 100644 --- a/src/main/webapp/app/core/interceptor/auth-expired.interceptor.ts +++ b/src/main/webapp/app/core/interceptor/auth-expired.interceptor.ts @@ -11,7 +11,7 @@ export class AuthExpiredInterceptor implements HttpInterceptor { intercept(request: HttpRequest, next: HttpHandler): Observable> { return next.handle(request).pipe( tap( - (event: HttpEvent) => {}, + () => {}, (err: any) => { if (err instanceof HttpErrorResponse) { if (err.status === 401) { diff --git a/src/main/webapp/app/core/interceptor/errorhandler.interceptor.ts b/src/main/webapp/app/core/interceptor/errorhandler.interceptor.ts index 1d5014a69ab9..e7b25806a3e3 100644 --- a/src/main/webapp/app/core/interceptor/errorhandler.interceptor.ts +++ b/src/main/webapp/app/core/interceptor/errorhandler.interceptor.ts @@ -11,7 +11,7 @@ export class ErrorHandlerInterceptor implements HttpInterceptor { intercept(request: HttpRequest, next: HttpHandler): Observable> { return next.handle(request).pipe( tap( - (event: HttpEvent) => {}, + () => {}, (err: any) => { if (err instanceof HttpErrorResponse) { if (!(err.status === 401 && (err.message === '' || (err.url && err.url.includes('/api/account'))))) { diff --git a/src/main/webapp/app/core/login/login.service.ts b/src/main/webapp/app/core/login/login.service.ts index 8b7d79ef3dc4..797a9aa833e6 100644 --- a/src/main/webapp/app/core/login/login.service.ts +++ b/src/main/webapp/app/core/login/login.service.ts @@ -26,7 +26,7 @@ export class LoginService { return new Promise((resolve, reject) => { this.authServerProvider.login(credentials).subscribe( (data) => { - this.accountService.identity(true).then((user) => { + this.accountService.identity(true).then(() => { this.websocketService.sendActivity(); resolve(data); }); diff --git a/src/main/webapp/app/core/websocket/websocket.service.ts b/src/main/webapp/app/core/websocket/websocket.service.ts index 36f71bebe2d0..3552779eea84 100644 --- a/src/main/webapp/app/core/websocket/websocket.service.ts +++ b/src/main/webapp/app/core/websocket/websocket.service.ts @@ -107,7 +107,7 @@ export class JhiWebsocketService implements IWebsocketService, OnDestroy { }; this.stompClient = over(socket, options); // Note: at the moment, debugging is deactivated to prevent console log statements - this.stompClient.debug = function (str) {}; + this.stompClient.debug = function () {}; const headers = {}; headers['X-CSRF-TOKEN'] = this.csrfService.getCSRF(); @@ -148,7 +148,7 @@ export class JhiWebsocketService implements IWebsocketService, OnDestroy { // Setup periodic logs of websocket connection numbers this.logTimers.push( - timer(0, 60000).subscribe((x) => { + timer(0, 60000).subscribe(() => { console.log('\n\n'); console.log(`${this.subscribers.size} websocket subscriptions: `, this.subscribers.keys()); // this.subscribers.forEach((sub, topic) => console.log(topic)); diff --git a/src/main/webapp/app/course/course-scores/course-scores.component.ts b/src/main/webapp/app/course/course-scores/course-scores.component.ts index e269609f60b5..a71e2fbc5e2e 100644 --- a/src/main/webapp/app/course/course-scores/course-scores.component.ts +++ b/src/main/webapp/app/course/course-scores/course-scores.component.ts @@ -404,7 +404,7 @@ export class CourseScoresComponent implements OnInit, OnDestroy { if (this.exerciseTitlesPerType.get(exerciseType) && this.exerciseTitlesPerType.get(exerciseType)!.length !== 0) { const exerciseTypeName = capitalizeFirstLetter(exerciseType); const exerciseTitleKeys = this.exerciseTitlesPerType.get(exerciseType)!; - exerciseTitleKeys.forEach((title, index) => { + exerciseTitleKeys.forEach((title) => { emptyLine[title] = ''; }); emptyLine[exerciseTypeName + ' ' + POINTS_KEY] = ''; diff --git a/src/main/webapp/app/course/manage/course-exercise-submission-result-simulation.service.ts b/src/main/webapp/app/course/manage/course-exercise-submission-result-simulation.service.ts index ec06b5c9fe55..116923d6ef48 100644 --- a/src/main/webapp/app/course/manage/course-exercise-submission-result-simulation.service.ts +++ b/src/main/webapp/app/course/manage/course-exercise-submission-result-simulation.service.ts @@ -1,4 +1,3 @@ -import { SERVER_API_URL } from 'app/app.constants'; import { Injectable } from '@angular/core'; import { ProgrammingSubmission } from 'app/entities/programming-submission.model'; import { Result } from 'app/entities/result.model'; diff --git a/src/main/webapp/app/course/manage/course-group.component.ts b/src/main/webapp/app/course/manage/course-group.component.ts index 3c638dadb8a3..07b8c2b06d4d 100644 --- a/src/main/webapp/app/course/manage/course-group.component.ts +++ b/src/main/webapp/app/course/manage/course-group.component.ts @@ -157,7 +157,7 @@ export class CourseGroupComponent implements OnInit, OnDestroy { // Flash green background color to signal to the user that this record was added this.flashRowClass(cssClasses.newlyAddedMember); }, - (err) => { + () => { this.isTransitioning = false; }, ); @@ -237,10 +237,8 @@ export class CourseGroupComponent implements OnInit, OnDestroy { /** * Computes the row class that is being added to all rows of the datatable - * - * @param row Row from ngx datatable */ - dataTableRowClass = (row: any) => { + dataTableRowClass = () => { return this.rowClass; }; diff --git a/src/main/webapp/app/course/manage/course-management.route.ts b/src/main/webapp/app/course/manage/course-management.route.ts index dcf8eecaf646..a6fca6386aab 100644 --- a/src/main/webapp/app/course/manage/course-management.route.ts +++ b/src/main/webapp/app/course/manage/course-management.route.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpResponse } from '@angular/common/http'; -import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { Observable, of } from 'rxjs'; import { filter, map } from 'rxjs/operators'; @@ -16,7 +16,7 @@ import { CourseGroupComponent } from 'app/course/manage/course-group.component'; export class CourseResolve implements Resolve { constructor(private service: CourseManagementService) {} - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + resolve(route: ActivatedRouteSnapshot): Observable { const id = route.params['courseId'] ? route.params['courseId'] : null; if (id) { return this.service.find(id).pipe( diff --git a/src/main/webapp/app/course/manage/course-management.service.ts b/src/main/webapp/app/course/manage/course-management.service.ts index 4202be157e80..b92200d17f70 100644 --- a/src/main/webapp/app/course/manage/course-management.service.ts +++ b/src/main/webapp/app/course/manage/course-management.service.ts @@ -206,11 +206,11 @@ export class CourseManagementService { } private reconnectObjects(res: EntityArrayResponseType): EntityArrayResponseType { - if (res.body) { + /*if (res.body) { res.body.forEach((course: Course) => { // TODO: implement }); - } + }*/ return res; } diff --git a/src/main/webapp/app/course/manage/course-update.component.ts b/src/main/webapp/app/course/manage/course-update.component.ts index 32c1f41d197f..85d2946f1c2d 100644 --- a/src/main/webapp/app/course/manage/course-update.component.ts +++ b/src/main/webapp/app/course/manage/course-update.component.ts @@ -145,7 +145,7 @@ export class CourseUpdateComponent implements OnInit { private subscribeToSaveResponse(result: Observable>) { result.subscribe( - (res: HttpResponse) => this.onSaveSuccess(), + () => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError(res), ); } @@ -197,7 +197,7 @@ export class CourseUpdateComponent implements OnInit { this.courseImageFile = null; this.courseImageFileName = result.path; }, - (error) => { + () => { this.isUploadingCourseImage = false; this.courseImageFile = null; this.courseImageFileName = this.course.courseIcon; diff --git a/src/main/webapp/app/entities/lti-outcome-url.model.ts b/src/main/webapp/app/entities/lti-outcome-url.model.ts deleted file mode 100644 index 78334782cc58..000000000000 --- a/src/main/webapp/app/entities/lti-outcome-url.model.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { BaseEntity } from 'app/shared/model/base-entity'; -import { User } from 'app/core/user/user.model'; -import { Exercise } from 'app/entities/exercise.model'; - -export class LtiOutcomeUrl implements BaseEntity { - public id: number; - public url: string; - public sourcedId: string; - public user: User; - public exercise: Exercise; - - constructor() {} -} diff --git a/src/main/webapp/app/entities/lti-user-id.model.ts b/src/main/webapp/app/entities/lti-user-id.model.ts deleted file mode 100644 index ddfdfdf07253..000000000000 --- a/src/main/webapp/app/entities/lti-user-id.model.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { BaseEntity } from 'app/shared/model/base-entity'; -import { User } from 'app/core/user/user.model'; - -export class LtiUserId implements BaseEntity { - public id: number; - public ltiUserId: string; - public user: User; - - constructor() {} -} diff --git a/src/main/webapp/app/entities/single-user-notification.model.ts b/src/main/webapp/app/entities/single-user-notification.model.ts deleted file mode 100644 index b79f2e22dbdf..000000000000 --- a/src/main/webapp/app/entities/single-user-notification.model.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { User } from 'app/core/user/user.model'; -import { Notification, NotificationType } from 'app/entities/notification.model'; - -export class SingleUserNotification extends Notification { - public id: number; - public recipient: User; - - constructor() { - super(NotificationType.SINGLE); - } -} diff --git a/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment-dashboard.component.ts b/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment-dashboard.component.ts index 17fc122f0223..6d6fac574b92 100644 --- a/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment-dashboard.component.ts +++ b/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment-dashboard.component.ts @@ -88,7 +88,11 @@ export class FileUploadAssessmentDashboardComponent implements OnInit { .subscribe((submissions: FileUploadSubmission[]) => { this.submissions = submissions; this.filteredSubmissions = submissions; - submissions.length > 0 ? resolve() : reject(); + if (submissions.length > 0) { + resolve(); + } else { + reject(); + } }); }); } diff --git a/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.html b/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.html index 73ea54880424..f2c30c735464 100644 --- a/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.html +++ b/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.html @@ -43,7 +43,7 @@

Feedback
diff --git a/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.ts b/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.ts index eba8f82ba264..d1101d45ef3a 100644 --- a/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.ts +++ b/src/main/webapp/app/exercises/file-upload/assess/file-upload-assessment.component.ts @@ -379,7 +379,7 @@ export class FileUploadAssessmentComponent implements OnInit, AfterViewInit, OnD } } - updateAssessment(assessment: Feedback) { + updateAssessment() { this.validateAssessment(); } @@ -467,7 +467,7 @@ export class FileUploadAssessmentComponent implements OnInit, AfterViewInit, OnD this.jhiAlertService.clear(); this.jhiAlertService.success('artemisApp.assessment.messages.updateAfterComplaintSuccessful'); }, - (error: HttpErrorResponse) => { + () => { this.jhiAlertService.clear(); this.jhiAlertService.error('artemisApp.assessment.messages.updateAfterComplaintFailed'); }, diff --git a/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-management.route.ts b/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-management.route.ts index f106603b5720..c74d25cee62d 100644 --- a/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-management.route.ts +++ b/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-management.route.ts @@ -1,4 +1,4 @@ -import { ActivatedRouteSnapshot, Resolve, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { FileUploadExerciseComponent } from './file-upload-exercise.component'; import { FileUploadExerciseDetailComponent } from './file-upload-exercise-detail.component'; @@ -9,7 +9,7 @@ import { Injectable, NgModule } from '@angular/core'; import { filter, map } from 'rxjs/operators'; import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; import { FileUploadExerciseUpdateComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-update.component'; -import { CourseManagementService } from '../../../course/manage/course-management.service'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; import { Course } from 'app/entities/course.model'; @Injectable({ providedIn: 'root' }) @@ -20,9 +20,8 @@ export class FileUploadExerciseResolve implements Resolve { * Resolves the route and initializes file upload exercise either from exerciseId (existing exercise) or * from course id (new exercise) * @param route - * @param state */ - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + resolve(route: ActivatedRouteSnapshot) { if (route.params['exerciseId']) { return this.fileUploadExerciseService.find(route.params['exerciseId']).pipe( filter((res) => !!res.body), diff --git a/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-update.component.ts b/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-update.component.ts index 92d07a0b92a4..09cfecca9d24 100644 --- a/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-update.component.ts +++ b/src/main/webapp/app/exercises/file-upload/manage/file-upload-exercise-update.component.ts @@ -5,7 +5,7 @@ import { Observable } from 'rxjs'; import { AlertService } from 'app/core/alert/alert.service'; import { FileUploadExerciseService } from './file-upload-exercise.service'; import { FileUploadExercise } from 'app/entities/file-upload-exercise.model'; -import { CourseManagementService } from '../../../course/manage/course-management.service'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; import { MAX_SCORE_PATTERN } from 'app/app.constants'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; import { ExerciseCategory } from 'app/entities/exercise.model'; @@ -95,7 +95,7 @@ export class FileUploadExerciseUpdateComponent implements OnInit { private subscribeToSaveResponse(result: Observable>) { result.subscribe( - (res: HttpResponse) => this.onSaveSuccess(), + () => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError(res), ); } diff --git a/src/main/webapp/app/exercises/file-upload/participate/file-upload-submission.service.ts b/src/main/webapp/app/exercises/file-upload/participate/file-upload-submission.service.ts index 578f5b64743a..a9d273f09dc6 100644 --- a/src/main/webapp/app/exercises/file-upload/participate/file-upload-submission.service.ts +++ b/src/main/webapp/app/exercises/file-upload/participate/file-upload-submission.service.ts @@ -1,8 +1,9 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; +import { map } from 'rxjs/operators'; -import { FileUploadSubmission } from '../../../entities/file-upload-submission.model'; +import { FileUploadSubmission } from 'app/entities/file-upload-submission.model'; import { createRequestOption } from 'app/shared/util/request-util'; import { stringifyCircular } from 'app/shared/util/utils'; @@ -28,7 +29,7 @@ export class FileUploadSubmissionService { .post(`api/exercises/${exerciseId}/file-upload-submissions`, formData, { observe: 'response', }) - .map((res: EntityResponseType) => this.convertResponse(res)); + .pipe(map((res: EntityResponseType) => this.convertResponse(res))); } /** @@ -40,7 +41,7 @@ export class FileUploadSubmissionService { .get(`api/file-upload-submissions/${fileUploadSubmissionId}`, { observe: 'response', }) - .map((res: HttpResponse) => this.convertResponse(res)); + .pipe(map((res: HttpResponse) => this.convertResponse(res))); } /** @@ -55,7 +56,7 @@ export class FileUploadSubmissionService { params: options, observe: 'response', }) - .map((res: HttpResponse) => this.convertArrayResponse(res)); + .pipe(map((res: HttpResponse) => this.convertArrayResponse(res))); } /** diff --git a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-conflict.component.ts b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-conflict.component.ts index ced3d74bb42a..42fa59e7d8de 100644 --- a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-conflict.component.ts +++ b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-conflict.component.ts @@ -124,10 +124,10 @@ export class ModelingAssessmentConflictComponent implements OnInit, AfterViewIni } this.modelingAssessmentService.saveAssessment(this.mergedFeedbacks, this.submissionId).subscribe( - (result) => { + () => { this.jhiAlertService.success('modelingAssessmentEditor.messages.saveSuccessful'); }, - (error) => this.jhiAlertService.error('modelingAssessmentEditor.messages.saveFailed'), + () => this.jhiAlertService.error('modelingAssessmentEditor.messages.saveFailed'), ); } @@ -143,9 +143,9 @@ export class ModelingAssessmentConflictComponent implements OnInit, AfterViewIni escalatedConflicts.push(this.conflicts![i]); } } - this.modelingAssessmentService.escalateConflict(escalatedConflicts).subscribe((value) => { + this.modelingAssessmentService.escalateConflict(escalatedConflicts).subscribe(() => { this.modelingAssessmentService.saveAssessment(this.mergedFeedbacks, this.submissionId, true).subscribe( - (result) => { + () => { this.jhiAlertService.success('modelingAssessmentEditor.messages.submitSuccessful'); this.router.navigate(['/course-management', this.courseId, 'modeling-exercises', this.modelingExercise.id, 'submissions', this.submissionId, 'assessment']); }, diff --git a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component.ts b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component.ts index 53492824333e..c02321b57ea4 100644 --- a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component.ts +++ b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-dashboard.component.ts @@ -143,7 +143,7 @@ export class ModelingAssessmentDashboardComponent implements OnInit, OnDestroy { this.nextOptimalSubmissionIds = optimal; this.applyFilter(); }, - (error) => { + () => { this.applyFilter(); }, ); diff --git a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component.ts b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component.ts index 35b7d1921d3a..91aa6847c08a 100644 --- a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component.ts +++ b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component.ts @@ -182,7 +182,7 @@ export class ModelingAssessmentEditorComponent implements OnInit { (res) => { this.complaint = res.body!; }, - (err: HttpErrorResponse) => { + () => { this.onError(); }, ); @@ -328,7 +328,7 @@ export class ModelingAssessmentEditorComponent implements OnInit { this.jhiAlertService.clear(); this.jhiAlertService.success('modelingAssessmentEditor.messages.updateAfterComplaintSuccessful'); }, - (error: HttpErrorResponse) => { + () => { this.jhiAlertService.clear(); this.jhiAlertService.error('modelingAssessmentEditor.messages.updateAfterComplaintFailed'); }, diff --git a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment.service.ts b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment.service.ts index a53f96642f91..1e25caa3c422 100644 --- a/src/main/webapp/app/exercises/modeling/assess/modeling-assessment.service.ts +++ b/src/main/webapp/app/exercises/modeling/assess/modeling-assessment.service.ts @@ -2,7 +2,7 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from 'app/app.constants'; -import { UMLElementType, UMLModel, UMLModelElementType, UMLRelationshipType } from '@ls1intum/apollon'; +import { UMLElementType, UMLModel, UMLRelationshipType } from '@ls1intum/apollon'; import { mergeMap } from 'rxjs/operators'; import { timer } from 'rxjs'; import * as moment from 'moment'; diff --git a/src/main/webapp/app/exercises/modeling/manage/example-modeling/example-modeling-submission.component.ts b/src/main/webapp/app/exercises/modeling/manage/example-modeling/example-modeling-submission.component.ts index 55c58a9c1375..2af93cef8d6c 100644 --- a/src/main/webapp/app/exercises/modeling/manage/example-modeling/example-modeling-submission.component.ts +++ b/src/main/webapp/app/exercises/modeling/manage/example-modeling/example-modeling-submission.component.ts @@ -15,7 +15,6 @@ import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service' import { ModelingAssessmentService } from 'app/exercises/modeling/assess/modeling-assessment.service'; import { ModelingSubmission } from 'app/entities/modeling-submission.model'; import { ModelingExercise } from 'app/entities/modeling-exercise.model'; -import { TutorParticipation } from 'app/entities/participation/tutor-participation.model'; import { ModelingAssessmentComponent } from 'app/exercises/modeling/assess/modeling-assessment.component'; @Component({ @@ -314,7 +313,7 @@ export class ExampleModelingSubmissionComponent implements OnInit { exampleSubmission.submission.result.feedbacks = this.feedbacks; this.tutorParticipationService.assessExampleSubmission(exampleSubmission, this.exerciseId).subscribe( - (res: HttpResponse) => { + () => { this.jhiAlertService.success('artemisApp.exampleSubmission.assessScore.success'); }, (error: HttpErrorResponse) => { @@ -333,7 +332,7 @@ export class ExampleModelingSubmissionComponent implements OnInit { } readAndUnderstood() { - this.tutorParticipationService.assessExampleSubmission(this.exampleSubmission, this.exerciseId).subscribe((res: HttpResponse) => { + this.tutorParticipationService.assessExampleSubmission(this.exampleSubmission, this.exerciseId).subscribe(() => { this.jhiAlertService.success('artemisApp.exampleSubmission.readSuccessfully'); this.back(); }); diff --git a/src/main/webapp/app/exercises/modeling/manage/modeling-exercise-update.component.ts b/src/main/webapp/app/exercises/modeling/manage/modeling-exercise-update.component.ts index 94f7e2052c43..a41845798a86 100644 --- a/src/main/webapp/app/exercises/modeling/manage/modeling-exercise-update.component.ts +++ b/src/main/webapp/app/exercises/modeling/manage/modeling-exercise-update.component.ts @@ -1,11 +1,11 @@ -import { Component, OnInit, Input } from '@angular/core'; +import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { JhiEventManager } from 'ng-jhipster'; -import { ModelingExercise } from '../../../entities/modeling-exercise.model'; +import { ModelingExercise } from 'app/entities/modeling-exercise.model'; import { ModelingExerciseService } from './modeling-exercise.service'; -import { CourseManagementService } from '../../../course/manage/course-management.service'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; import { ExampleSubmissionService } from 'app/exercises/shared/example-submission/example-submission.service'; import { MAX_SCORE_PATTERN } from 'app/app.constants'; import { WindowRef } from 'app/core/websocket/window.service'; @@ -126,12 +126,12 @@ export class ModelingExerciseUpdateComponent implements OnInit { private subscribeToSaveResponse(result: Observable>): void { result.subscribe( - (res: HttpResponse) => this.onSaveSuccess(res.body!), - (res: HttpErrorResponse) => this.onSaveError(), + () => this.onSaveSuccess(), + () => this.onSaveError(), ); } - private onSaveSuccess(result: ModelingExercise): void { + private onSaveSuccess(): void { this.eventManager.broadcast({ name: 'modelingExerciseListModification', content: 'OK' }); this.isSaving = false; this.previousState(); diff --git a/src/main/webapp/app/exercises/modeling/manage/modeling-exercise.route.ts b/src/main/webapp/app/exercises/modeling/manage/modeling-exercise.route.ts index dd9b04185944..259fb97906ac 100644 --- a/src/main/webapp/app/exercises/modeling/manage/modeling-exercise.route.ts +++ b/src/main/webapp/app/exercises/modeling/manage/modeling-exercise.route.ts @@ -1,5 +1,5 @@ import { Injectable, NgModule } from '@angular/core'; -import { ActivatedRouteSnapshot, Resolve, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { ModelingExerciseComponent } from './modeling-exercise.component'; import { ModelingExerciseDetailComponent } from './modeling-exercise-detail.component'; @@ -15,7 +15,7 @@ import { Course } from 'app/entities/course.model'; @Injectable({ providedIn: 'root' }) export class ModelingExerciseResolver implements Resolve { constructor(private modelingExerciseService: ModelingExerciseService, private courseService: CourseManagementService) {} - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + resolve(route: ActivatedRouteSnapshot) { if (route.params['exerciseId']) { return this.modelingExerciseService.find(route.params['exerciseId']).pipe( filter((res) => !!res.body), @@ -31,7 +31,7 @@ export class ModelingExerciseResolver implements Resolve { } } -const routes: Routes = [ +export const routes: Routes = [ { path: ':courseId/modeling-exercises/new', component: ModelingExerciseUpdateComponent, diff --git a/src/main/webapp/app/exercises/modeling/participate/modeling-submission.component.ts b/src/main/webapp/app/exercises/modeling/participate/modeling-submission.component.ts index 9d7b1b9e395a..938898acb8f9 100644 --- a/src/main/webapp/app/exercises/modeling/participate/modeling-submission.component.ts +++ b/src/main/webapp/app/exercises/modeling/participate/modeling-submission.component.ts @@ -28,7 +28,6 @@ import { ButtonType } from 'app/shared/components/button.component'; import { participationStatus } from 'app/exercises/shared/exercise/exercise-utils'; import { filter } from 'rxjs/operators'; import { stringifyIgnoringFields } from 'app/shared/util/utils'; -import { Location } from '@angular/common'; import { Subject } from 'rxjs'; @Component({ diff --git a/src/main/webapp/app/exercises/modeling/participate/modeling-submission.service.ts b/src/main/webapp/app/exercises/modeling/participate/modeling-submission.service.ts index b12f05c42418..9206be6a6fef 100644 --- a/src/main/webapp/app/exercises/modeling/participate/modeling-submission.service.ts +++ b/src/main/webapp/app/exercises/modeling/participate/modeling-submission.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from 'app/app.constants'; +import { map } from 'rxjs/operators'; import { ModelingSubmission } from 'app/entities/modeling-submission.model'; import { createRequestOption } from 'app/shared/util/request-util'; @@ -21,7 +22,7 @@ export class ModelingSubmissionService { .post(`api/exercises/${exerciseId}/modeling-submissions`, copy, { observe: 'response', }) - .map((res: EntityResponseType) => this.convertResponse(res)); + .pipe(map((res: EntityResponseType) => this.convertResponse(res))); } update(modelingSubmission: ModelingSubmission, exerciseId: number): Observable { @@ -31,7 +32,7 @@ export class ModelingSubmissionService { headers: { 'Content-Type': 'application/json' }, observe: 'response', }) - .map((res: EntityResponseType) => this.convertResponse(res)); + .pipe(map((res: EntityResponseType) => this.convertResponse(res))); } getModelingSubmissionsForExercise(exerciseId: number, req?: any): Observable> { @@ -41,7 +42,7 @@ export class ModelingSubmissionService { params: options, observe: 'response', }) - .map((res: HttpResponse) => this.convertArrayResponse(res)); + .pipe(map((res: HttpResponse) => this.convertArrayResponse(res))); } getModelingSubmissionForExerciseWithoutAssessment(exerciseId: number, lock?: boolean): Observable { diff --git a/src/main/webapp/app/exercises/programming/assess/repo-export/programming-assessment-repo-export-dialog.component.ts b/src/main/webapp/app/exercises/programming/assess/repo-export/programming-assessment-repo-export-dialog.component.ts index 4d3912cd368e..79ec05954115 100644 --- a/src/main/webapp/app/exercises/programming/assess/repo-export/programming-assessment-repo-export-dialog.component.ts +++ b/src/main/webapp/app/exercises/programming/assess/repo-export/programming-assessment-repo-export-dialog.component.ts @@ -74,11 +74,9 @@ export class ProgrammingAssessmentRepoExportDialogComponent implements OnInit { if (this.participationIdList) { // We anonymize the assessment process ("double-blind"). this.repositoryExportOptions.addParticipantName = false; - this.repoExportService - .exportReposByParticipations(exerciseId, this.participationIdList, this.repositoryExportOptions) - .subscribe(this.handleExportRepoResponse, (err) => { - this.exportInProgress = false; - }); + this.repoExportService.exportReposByParticipations(exerciseId, this.participationIdList, this.repositoryExportOptions).subscribe(this.handleExportRepoResponse, () => { + this.exportInProgress = false; + }); return; } const participantIdentifierList = @@ -86,7 +84,7 @@ export class ProgrammingAssessmentRepoExportDialogComponent implements OnInit { this.repoExportService .exportReposByParticipantIdentifiers(exerciseId, participantIdentifierList, this.repositoryExportOptions) - .subscribe(this.handleExportRepoResponse, (err) => { + .subscribe(this.handleExportRepoResponse, () => { this.exportInProgress = false; }); } diff --git a/src/main/webapp/app/exercises/programming/manage/programming-exercise-management-routing.module.ts b/src/main/webapp/app/exercises/programming/manage/programming-exercise-management-routing.module.ts index b67348d801ad..d1a0f302247d 100644 --- a/src/main/webapp/app/exercises/programming/manage/programming-exercise-management-routing.module.ts +++ b/src/main/webapp/app/exercises/programming/manage/programming-exercise-management-routing.module.ts @@ -1,4 +1,4 @@ -import { ActivatedRouteSnapshot, Resolve, RouterModule, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, RouterModule, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { Injectable, NgModule } from '@angular/core'; import { ProgrammingExerciseDetailComponent } from 'app/exercises/programming/manage/programming-exercise-detail.component'; @@ -15,7 +15,7 @@ import { Observable } from 'rxjs/Observable'; export class ProgrammingExerciseResolve implements Resolve { constructor(private service: ProgrammingExerciseService) {} - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + resolve(route: ActivatedRouteSnapshot) { const id = route.params['id'] ? route.params['id'] : null; if (id) { return this.service.find(id).pipe(map((programmingExercise: HttpResponse) => programmingExercise.body!)); @@ -24,7 +24,7 @@ export class ProgrammingExerciseResolve implements Resolve } } -const routes: Routes = [ +export const routes: Routes = [ { path: ':courseId/programming-exercises/new', component: ProgrammingExerciseUpdateComponent, diff --git a/src/main/webapp/app/exercises/programming/manage/programming-exercise.component.ts b/src/main/webapp/app/exercises/programming/manage/programming-exercise.component.ts index f7b7ba6a2141..3f651a9396c3 100644 --- a/src/main/webapp/app/exercises/programming/manage/programming-exercise.component.ts +++ b/src/main/webapp/app/exercises/programming/manage/programming-exercise.component.ts @@ -115,7 +115,7 @@ export class ProgrammingExerciseComponent extends ExerciseComponent implements O (result: ProgrammingExercise) => { this.router.navigate(['course-management', this.courseId, 'programming-exercises', 'import', result.id]); }, - (reason) => {}, + () => {}, ); } diff --git a/src/main/webapp/app/exercises/programming/manage/test-cases/programming-exercise-manage-test-cases.component.ts b/src/main/webapp/app/exercises/programming/manage/test-cases/programming-exercise-manage-test-cases.component.ts index a3283e4960d3..2cede78ea6f2 100644 --- a/src/main/webapp/app/exercises/programming/manage/test-cases/programming-exercise-manage-test-cases.component.ts +++ b/src/main/webapp/app/exercises/programming/manage/test-cases/programming-exercise-manage-test-cases.component.ts @@ -1,7 +1,6 @@ import { Component, OnDestroy, OnInit, ViewEncapsulation } from '@angular/core'; import { TranslateService } from '@ngx-translate/core'; import { ActivatedRoute } from '@angular/router'; -import { HttpErrorResponse } from '@angular/common/http'; import { of, Subscription, zip } from 'rxjs'; import { catchError, distinctUntilChanged, map, take, tap } from 'rxjs/operators'; import { differenceBy as _differenceBy, differenceWith as _differenceWith, intersectionWith as _intersectionWith, unionBy as _unionBy } from 'lodash'; @@ -232,7 +231,7 @@ export class ProgrammingExerciseManageTestCasesComponent implements OnInit, OnDe this.alertService.success(`artemisApp.programmingExercise.manageTestCases.testCasesUpdated`); } }), - catchError((err: HttpErrorResponse) => { + catchError(() => { this.alertService.error(`artemisApp.programmingExercise.manageTestCases.testCasesCouldNotBeUpdated`, { testCases: testCasesToUpdate }); return of(null); }), @@ -261,6 +260,7 @@ export class ProgrammingExerciseManageTestCasesComponent implements OnInit, OnDe const existsUnchangedWithCustomWeight = this.testCases.filter(({ id }) => !this.changedTestCaseIds.includes(id)).some(({ weight }) => weight > 1); // If the updated weights are unsaved, we can just reset them locally in the browser without contacting the server. if (!existsUnchangedWithCustomWeight) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars this.testCases = this.testCases.map(({ weight, ...rest }) => ({ weight: 1, ...rest })); return; } @@ -272,7 +272,7 @@ export class ProgrammingExerciseManageTestCasesComponent implements OnInit, OnDe this.alertService.success(`artemisApp.programmingExercise.manageTestCases.weightsReset`); this.testCaseService.notifyTestCases(this.exercise.id, testCases); }), - catchError((err: HttpErrorResponse) => { + catchError(() => { this.alertService.error(`artemisApp.programmingExercise.manageTestCases.weightsResetFailed`); return of(null); }), diff --git a/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-test-schedule-date-picker.component.ts b/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-test-schedule-date-picker.component.ts index 4f85cdb642c1..ba319c96bb1e 100644 --- a/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-test-schedule-date-picker.component.ts +++ b/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-test-schedule-date-picker.component.ts @@ -30,9 +30,9 @@ export class ProgrammingExerciseTestScheduleDatePickerComponent implements Contr this._onChange = fn; } - registerOnTouched(fn: any): void {} + registerOnTouched(): void {} - setDisabledState(isDisabled: boolean): void {} + setDisabledState(): void {} writeValue(obj: any): void { if (obj !== undefined && this.selectedDate !== obj) { diff --git a/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.component.ts b/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.component.ts index da2fe0200559..2b3b48eef3f9 100644 --- a/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.component.ts +++ b/src/main/webapp/app/exercises/programming/manage/update/programming-exercise-update.component.ts @@ -16,7 +16,6 @@ import { AssessmentType } from 'app/entities/assessment-type.model'; import { ExerciseCategory } from 'app/entities/exercise.model'; import { EditorMode } from 'app/shared/markdown-editor/markdown-editor.component'; import { KatexCommand } from 'app/shared/markdown-editor/commands/katex.command'; -import { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model'; import { ProfileService } from 'app/shared/layouts/profiles/profile.service'; import { ProgrammingExerciseSimulationService } from 'app/exercises/programming/manage/services/programming-exercise-simulation.service'; @@ -190,7 +189,7 @@ export class ProgrammingExerciseUpdateComponent implements OnInit { private subscribeToSaveResponse(result: Observable>) { result.subscribe( - (res: HttpResponse) => this.onSaveSuccess(), + () => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError(res), ); } diff --git a/src/main/webapp/app/exercises/programming/participate/code-editor-student-container.component.ts b/src/main/webapp/app/exercises/programming/participate/code-editor-student-container.component.ts index f0a3a498c633..bdddfc009f1f 100644 --- a/src/main/webapp/app/exercises/programming/participate/code-editor-student-container.component.ts +++ b/src/main/webapp/app/exercises/programming/participate/code-editor-student-container.component.ts @@ -91,7 +91,7 @@ export class CodeEditorStudentContainerComponent extends CodeEditorContainer imp this.loadingParticipation = false; this.guidedTourService.enableTourForExercise(this.exercise, codeEditorTour, true); }, - (err) => { + () => { this.participationCouldNotBeFetched = true; this.loadingParticipation = false; }, diff --git a/src/main/webapp/app/exercises/programming/participate/programming-submission.service.ts b/src/main/webapp/app/exercises/programming/participate/programming-submission.service.ts index cdf87f7af85f..734c8abbcfc7 100644 --- a/src/main/webapp/app/exercises/programming/participate/programming-submission.service.ts +++ b/src/main/webapp/app/exercises/programming/participate/programming-submission.service.ts @@ -74,7 +74,7 @@ export class ProgrammingSubmissionService implements IProgrammingSubmissionServi ngOnDestroy(): void { Object.values(this.resultSubscriptions).forEach((sub) => sub.unsubscribe()); Object.values(this.resultTimerSubscriptions).forEach((sub) => sub.unsubscribe()); - this.submissionTopicsSubscribed.forEach((topic, _) => this.websocketService.unsubscribe(topic)); + this.submissionTopicsSubscribed.forEach((topic) => this.websocketService.unsubscribe(topic)); } get exerciseBuildState() { @@ -538,7 +538,7 @@ export class ProgrammingSubmissionService implements IProgrammingSubmissionServi this.resultSubscriptions = {}; Object.values(this.resultTimerSubscriptions).forEach((sub) => sub.unsubscribe()); this.resultTimerSubscriptions = {}; - this.submissionTopicsSubscribed.forEach((topic, _) => this.websocketService.unsubscribe(topic)); + this.submissionTopicsSubscribed.forEach((topic) => this.websocketService.unsubscribe(topic)); this.submissionTopicsSubscribed.forEach((_, participationId) => this.participationWebsocketService.unsubscribeForLatestResultOfParticipation(participationId, exercise)); this.submissionTopicsSubscribed.clear(); this.submissionSubjects = {}; diff --git a/src/main/webapp/app/exercises/programming/shared/code-editor/layout/code-editor-grid.component.ts b/src/main/webapp/app/exercises/programming/shared/code-editor/layout/code-editor-grid.component.ts index 685cb9e5aab0..2ca81a847bcc 100644 --- a/src/main/webapp/app/exercises/programming/shared/code-editor/layout/code-editor-grid.component.ts +++ b/src/main/webapp/app/exercises/programming/shared/code-editor/layout/code-editor-grid.component.ts @@ -167,6 +167,7 @@ export class CodeEditorGridComponent implements AfterViewInit { * @param minWidth {number} Width to set the element to after toggling the collapse * @param minHeight {number} Height to set the element to after toggling the collapse */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars toggleCollapse($event: any, horizontal: boolean, interactResizable: Interactable, minWidth?: number, minHeight?: number) { const target = $event.toElement || $event.relatedTarget || $event.target; target.blur(); diff --git a/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension.ts b/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension.ts index 8258acbb8b0c..cc81c56a0da8 100644 --- a/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension.ts +++ b/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension.ts @@ -48,7 +48,7 @@ export class ProgrammingExercisePlantUmlExtensionWrapper implements ArtemisShowd getExtension() { const extension: showdown.ShowdownExtension = { type: 'lang', - filter: (text: string, converter: showdown.Converter, options: showdown.ConverterOptions) => { + filter: (text: string) => { const idPlaceholder = '%idPlaceholder%'; // E.g. [task][Implement BubbleSort](testBubbleSort) const plantUmlRegex = /@startuml([^@]*)@enduml/g; diff --git a/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-task.extension.ts b/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-task.extension.ts index 39631e16b5ea..767683248e65 100644 --- a/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-task.extension.ts +++ b/src/main/webapp/app/exercises/programming/shared/instructions-render/extensions/programming-exercise-task.extension.ts @@ -65,7 +65,7 @@ export class ProgrammingExerciseTaskExtensionWrapper implements ArtemisShowdownE getExtension() { const extension: showdown.ShowdownExtension = { type: 'lang', - filter: (text: string, converter: showdown.Converter, options: showdown.ConverterOptions) => { + filter: (text: string) => { const idPlaceholder = '%idPlaceholder%'; // E.g. [task][Implement BubbleSort](testBubbleSort) const taskRegex = /\[task\]\[.*\]\(.*\)({.*})?/g; @@ -92,7 +92,7 @@ export class ProgrammingExerciseTaskExtensionWrapper implements ArtemisShowdownE // Emit new found elements that need to be injected into html after it is rendered. this.injectableElementsFoundSubject.next(() => this.injectTasks(testsForTask)); return testsForTask.reduce( - (acc: string, { completeString: task, taskName, tests }, index: number): string => + (acc: string, { completeString: task }, index: number): string => // Insert anchor divs into the text so that injectable elements can be inserted into them. acc.replace(new RegExp(escapeStringForUseInRegex(task), 'g'), taskContainer.replace(idPlaceholder, index.toString())), text, diff --git a/src/main/webapp/app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service.ts b/src/main/webapp/app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service.ts index 3a90da2dfba9..3bc6da90c4cb 100644 --- a/src/main/webapp/app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service.ts +++ b/src/main/webapp/app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service.ts @@ -27,7 +27,6 @@ export class ProgrammingExerciseInstructionService { * @param latestResult */ public testStatusForTask = (tests: string[], latestResult: Result | null): TaskResult => { - const totalTests = tests.length; if (latestResult && latestResult.successful && (!latestResult.feedbacks || !latestResult.feedbacks.length)) { // Case 1: Submission fulfills all test cases and there are no feedbacks (legacy case), no further checking needed. return { testCaseState: TestCaseState.SUCCESS, detailed: { successfulTests: tests, failedTests: [], notExecutedTests: [] } }; diff --git a/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-create-form.component.ts b/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-create-form.component.ts index 164b161263de..e8159de80eed 100644 --- a/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-create-form.component.ts +++ b/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-create-form.component.ts @@ -36,7 +36,7 @@ export class ApollonDiagramCreateFormComponent implements AfterViewInit { this.dismiss(); this.router.navigate(['course-management', 'apollon-diagrams', newDiagram.id]); }, - (response) => { + () => { this.jhiAlertService.error('artemisApp.apollonDiagram.create.error'); }, ); diff --git a/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-list.component.ts b/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-list.component.ts index dd2db10cecbf..89728bd9ccf6 100644 --- a/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-list.component.ts +++ b/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/apollon-diagram-list.component.ts @@ -36,7 +36,7 @@ export class ApollonDiagramListComponent implements OnInit { (response) => { this.apollonDiagrams = response.body!; }, - (response) => { + () => { this.jhiAlertService.error('artemisApp.apollonDiagram.home.error.loading'); }, ); @@ -58,13 +58,13 @@ export class ApollonDiagramListComponent implements OnInit { */ delete(apollonDiagram: ApollonDiagram) { this.apollonDiagramsService.delete(apollonDiagram.id).subscribe( - (response) => { + () => { this.jhiAlertService.success('artemisApp.apollonDiagram.delete.success', { title: apollonDiagram.title }); this.apollonDiagrams = this.apollonDiagrams.filter((diagram) => { return diagram.id !== apollonDiagram.id; }); }, - (response) => { + () => { this.jhiAlertService.error('artemisApp.apollonDiagram.delete.error', { title: apollonDiagram.title }); }, ); diff --git a/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/exercise-generation/quiz-exercise-generator.ts b/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/exercise-generation/quiz-exercise-generator.ts index 21a28852950e..4796daf532d4 100644 --- a/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/exercise-generation/quiz-exercise-generator.ts +++ b/src/main/webapp/app/exercises/quiz/manage/apollon-diagrams/exercise-generation/quiz-exercise-generator.ts @@ -300,7 +300,7 @@ function createCorrectMappings(dragItems: Map, dropLocations: if (!dragElement || !dragElement.name) { continue; } - for (const [dropLocationElementId, _] of dropLocations.entries()) { + for (const [dropLocationElementId] of dropLocations.entries()) { const dropElement = textualElements.find((element) => element.id === dropLocationElementId); if (!dropElement || dropElement.id === dragElement.id || dropElement.owner === dragElement.owner || dropElement.name !== dragElement.name) { continue; diff --git a/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-detail.component.ts b/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-detail.component.ts index 54af857d8b56..dd1e0d374c4b 100644 --- a/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-detail.component.ts +++ b/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-detail.component.ts @@ -957,7 +957,7 @@ export class QuizExerciseDetailComponent implements OnInit, OnChanges, Component this.onSaveError(); } }, - (res: HttpErrorResponse) => this.onSaveError(res), + () => this.onSaveError(), ); this.pendingChangesCache = false; } else { @@ -969,7 +969,7 @@ export class QuizExerciseDetailComponent implements OnInit, OnChanges, Component this.onSaveError(); } }, - (res: HttpErrorResponse) => this.onSaveError(res), + () => this.onSaveError(), ); this.pendingChangesCache = false; } @@ -993,7 +993,7 @@ export class QuizExerciseDetailComponent implements OnInit, OnChanges, Component * @function onSaveError * @desc Callback function for when the save fails */ - private onSaveError = (error?: HttpErrorResponse): void => { + private onSaveError = (): void => { console.error('Saving Quiz Failed! Please try again later.'); this.jhiAlertService.error('artemisApp.quizExercise.saveError'); this.isSaving = false; diff --git a/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-popup.service.ts b/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-popup.service.ts index c81b4a59c152..0c1723d58e74 100644 --- a/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-popup.service.ts +++ b/src/main/webapp/app/exercises/quiz/manage/quiz-exercise-popup.service.ts @@ -13,7 +13,7 @@ export class QuizExercisePopupService { } open(component: Component, quizExercise: QuizExercise): Promise { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { if (this.ngbModalRef == null) { this.ngbModalRef = this.quizExerciseModalRef(component, quizExercise); } @@ -33,7 +33,7 @@ export class QuizExercisePopupService { this.ngbModalRef = null; } }, - (reason) => { + () => { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, diff --git a/src/main/webapp/app/exercises/quiz/manage/quiz-exercise.service.ts b/src/main/webapp/app/exercises/quiz/manage/quiz-exercise.service.ts index 16cc722da7ca..41cb316f2869 100644 --- a/src/main/webapp/app/exercises/quiz/manage/quiz-exercise.service.ts +++ b/src/main/webapp/app/exercises/quiz/manage/quiz-exercise.service.ts @@ -4,7 +4,7 @@ import { Observable } from 'rxjs/Observable'; import { map } from 'rxjs/operators'; import { SERVER_API_URL } from 'app/app.constants'; -import { QuizExercise } from '../../../entities/quiz/quiz-exercise.model'; +import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; import { createRequestOption } from 'app/shared/util/request-util'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; import { QuizQuestion } from 'app/entities/quiz/quiz-question.model'; @@ -88,7 +88,7 @@ export class QuizExerciseService { .pipe(map((res: EntityResponseType) => this.exerciseService.convertDateFromServer(res))); } - query(req?: any): Observable { + query(): Observable { return this.http .get(this.resourceUrl, { observe: 'response' }) .pipe(map((res: EntityArrayResponseType) => this.exerciseService.convertDateArrayFromServer(res))); diff --git a/src/main/webapp/app/exercises/quiz/manage/re-evaluate/quiz-re-evaluate-warning.component.ts b/src/main/webapp/app/exercises/quiz/manage/re-evaluate/quiz-re-evaluate-warning.component.ts index af01b71aa3e2..96bcb3738c02 100644 --- a/src/main/webapp/app/exercises/quiz/manage/re-evaluate/quiz-re-evaluate-warning.component.ts +++ b/src/main/webapp/app/exercises/quiz/manage/re-evaluate/quiz-re-evaluate-warning.component.ts @@ -43,7 +43,7 @@ export class QuizReEvaluateWarningComponent implements OnInit { this.isSaving = false; this.quizExerciseService.find(this.quizExercise.id).subscribe((res) => { this.backUpQuiz = res.body!; - this.loadQuizSuccess(this.quizExercise); + this.loadQuizSuccess(); }); } @@ -66,10 +66,8 @@ export class QuizReEvaluateWarningComponent implements OnInit { * 3. check for each question-element if: * - it is set invalid * - the correctness was changed - * - * @param quiz {quizExercise} the reference Quiz from Server */ - loadQuizSuccess(quiz: QuizExercise): void { + loadQuizSuccess(): void { // question deleted? this.questionDeleted = this.backUpQuiz.quizQuestions.length !== this.quizExercise.quizQuestions.length; @@ -250,7 +248,7 @@ export class QuizReEvaluateWarningComponent implements OnInit { this.busy = true; this.quizReEvaluateService.update(this.quizExercise).subscribe( - (res) => { + () => { this.busy = false; this.successful = true; }, diff --git a/src/main/webapp/app/exercises/quiz/manage/statistics/quiz-point-statistic/quiz-point-statistic.component.ts b/src/main/webapp/app/exercises/quiz/manage/statistics/quiz-point-statistic/quiz-point-statistic.component.ts index 91aa1358ffd7..aa7698029a01 100644 --- a/src/main/webapp/app/exercises/quiz/manage/statistics/quiz-point-statistic/quiz-point-statistic.component.ts +++ b/src/main/webapp/app/exercises/quiz/manage/statistics/quiz-point-statistic/quiz-point-statistic.component.ts @@ -84,7 +84,7 @@ export class QuizPointStatisticComponent implements OnInit, OnDestroy, DataSetPr this.loadQuizSuccess(quiz); } }, - (error) => {}, + () => {}, ); } diff --git a/src/main/webapp/app/exercises/quiz/participate/quiz-participation.component.ts b/src/main/webapp/app/exercises/quiz/participate/quiz-participation.component.ts index e06de92a6b3c..4ca6e2829335 100644 --- a/src/main/webapp/app/exercises/quiz/participate/quiz-participation.component.ts +++ b/src/main/webapp/app/exercises/quiz/participate/quiz-participation.component.ts @@ -350,7 +350,7 @@ export class QuizParticipationComponent implements OnInit, OnDestroy { this.applyQuizFull(payload); } }, - (error) => {}, + () => {}, ); } } diff --git a/src/main/webapp/app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component.ts b/src/main/webapp/app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component.ts index 6226ae3bac85..661abb28e7e7 100644 --- a/src/main/webapp/app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component.ts +++ b/src/main/webapp/app/exercises/quiz/shared/questions/drag-and-drop-question/drag-and-drop-question.component.ts @@ -1,4 +1,4 @@ -import { Component, EventEmitter, HostListener, Input, OnChanges, Output, SimpleChanges, ViewChild, ViewEncapsulation } from '@angular/core'; +import { Component, EventEmitter, HostListener, Input, OnChanges, Output, ViewChild, ViewEncapsulation } from '@angular/core'; import { ArtemisMarkdownService } from 'app/shared/markdown.service'; import { DragAndDropQuestionUtil } from 'app/exercises/quiz/shared/drag-and-drop-question-util.service'; import { polyfill } from 'mobile-drag-drop'; @@ -16,12 +16,6 @@ polyfill({ dragImageTranslateOverride: scrollBehaviourDragImageTranslateOverride, }); -// Drag-enter listener for mobile devices -// tslint:disable-next-line -(event: any) => { - event.preventDefault(); -}; - window.addEventListener('touchmove', function () {}, { passive: false }); @Component({ @@ -87,7 +81,7 @@ export class DragAndDropQuestionComponent implements OnChanges { resizeImage(); } - ngOnChanges(changes: SimpleChanges): void { + ngOnChanges(): void { this.countCorrectMappings(); } diff --git a/src/main/webapp/app/exercises/shared/dashboards/tutor/tutor-exercise-dashboard.component.ts b/src/main/webapp/app/exercises/shared/dashboards/tutor/tutor-exercise-dashboard.component.ts index 131d47c61952..7d7949bd272a 100644 --- a/src/main/webapp/app/exercises/shared/dashboards/tutor/tutor-exercise-dashboard.component.ts +++ b/src/main/webapp/app/exercises/shared/dashboards/tutor/tutor-exercise-dashboard.component.ts @@ -377,7 +377,7 @@ export class TutorExerciseDashboardComponent implements OnInit, AfterViewInit { modalRef.componentInstance.exercise = this.exercise; modalRef.componentInstance.onResultModified.subscribe(() => this.loadAll()); modalRef.result.then( - (_) => this.loadAll(), + () => this.loadAll(), () => {}, ); return; diff --git a/src/main/webapp/app/exercises/shared/exercise-headers/difficulty-badge.component.ts b/src/main/webapp/app/exercises/shared/exercise-headers/difficulty-badge.component.ts index 960c9ab671b7..e772a5114819 100644 --- a/src/main/webapp/app/exercises/shared/exercise-headers/difficulty-badge.component.ts +++ b/src/main/webapp/app/exercises/shared/exercise-headers/difficulty-badge.component.ts @@ -1,5 +1,5 @@ import { Component, Input, OnDestroy, OnInit } from '@angular/core'; -import { LangChangeEvent, TranslateService } from '@ngx-translate/core'; +import { TranslateService } from '@ngx-translate/core'; import { Subscription } from 'rxjs/Subscription'; import { DifficultyLevel, Exercise } from 'app/entities/exercise.model'; @@ -17,7 +17,7 @@ export class DifficultyBadgeComponent implements OnInit, OnDestroy { constructor(private translateService: TranslateService) {} ngOnInit(): void { - this.translateSubscription = this.translateService.onLangChange.subscribe((event: LangChangeEvent) => { + this.translateSubscription = this.translateService.onLangChange.subscribe(() => { this.setBadgeAttributes(); }); this.setBadgeAttributes(); diff --git a/src/main/webapp/app/exercises/shared/exercise-headers/header-exercise-page-with-details.component.ts b/src/main/webapp/app/exercises/shared/exercise-headers/header-exercise-page-with-details.component.ts index 80e99c09aaf8..dfce6e9b3072 100644 --- a/src/main/webapp/app/exercises/shared/exercise-headers/header-exercise-page-with-details.component.ts +++ b/src/main/webapp/app/exercises/shared/exercise-headers/header-exercise-page-with-details.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core'; +import { Component, Input, OnChanges, OnInit } from '@angular/core'; import * as moment from 'moment'; import { Exercise, ExerciseCategory, getIcon } from 'app/entities/exercise.model'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; @@ -24,7 +24,7 @@ export class HeaderExercisePageWithDetailsComponent implements OnInit, OnChanges this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise); } - ngOnChanges(changes: SimpleChanges): void { + ngOnChanges(): void { this.setExerciseStatusBadge(); this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise); } diff --git a/src/main/webapp/app/exercises/shared/exercise-headers/header-participation-page.component.ts b/src/main/webapp/app/exercises/shared/exercise-headers/header-participation-page.component.ts index db76499bec16..c5cce59b44ab 100644 --- a/src/main/webapp/app/exercises/shared/exercise-headers/header-participation-page.component.ts +++ b/src/main/webapp/app/exercises/shared/exercise-headers/header-participation-page.component.ts @@ -1,4 +1,4 @@ -import { Component, Input, OnChanges, OnInit, SimpleChanges, ViewEncapsulation } from '@angular/core'; +import { Component, Input, OnChanges, OnInit, ViewEncapsulation } from '@angular/core'; import * as moment from 'moment'; import { Exercise, ExerciseCategory, getIcon } from 'app/entities/exercise.model'; import { ExerciseService } from 'app/exercises/shared/exercise/exercise.service'; @@ -30,7 +30,7 @@ export class HeaderParticipationPageComponent implements OnInit, OnChanges { this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise); } - ngOnChanges(changes: SimpleChanges): void { + ngOnChanges(): void { this.setExerciseStatusBadge(); this.exerciseCategories = this.exerciseService.convertExerciseCategoriesFromServer(this.exercise); } diff --git a/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint-update.component.ts b/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint-update.component.ts index 14ef8ef17842..c1e58cb75906 100644 --- a/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint-update.component.ts +++ b/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint-update.component.ts @@ -61,7 +61,7 @@ export class ExerciseHintUpdateComponent implements OnInit, OnDestroy { return of(null); }), ) - .subscribe((res: Exercise) => { + .subscribe(() => { this.isLoading = false; }); } else { diff --git a/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.component.ts b/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.component.ts index b37350a96a0e..307c05b2bcdd 100644 --- a/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.component.ts +++ b/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.component.ts @@ -76,7 +76,7 @@ export class ExerciseHintComponent implements OnInit, OnDestroy { if (this.eventSubscriber) { this.eventSubscriber.unsubscribe(); } - this.eventSubscriber = this.eventManager.subscribe('exerciseHintListModification', (response: any) => this.loadAllByExerciseId()); + this.eventSubscriber = this.eventManager.subscribe('exerciseHintListModification', () => this.loadAllByExerciseId()); } /** diff --git a/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.route.ts b/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.route.ts index 3f27c047f530..46cb87b77227 100644 --- a/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.route.ts +++ b/src/main/webapp/app/exercises/shared/exercise-hint/manage/exercise-hint.route.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpResponse } from '@angular/common/http'; -import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { Observable, of } from 'rxjs'; import { filter, map } from 'rxjs/operators'; @@ -14,7 +14,7 @@ import { ExerciseHint } from 'app/entities/exercise-hint.model'; export class ExerciseHintResolve implements Resolve { constructor(private service: ExerciseHintService) {} - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + resolve(route: ActivatedRouteSnapshot): Observable { const id = route.params['hintId'] ? route.params['hintId'] : null; if (id) { return this.service.find(id).pipe( diff --git a/src/main/webapp/app/exercises/shared/exercise/exercise-popup.service.ts b/src/main/webapp/app/exercises/shared/exercise/exercise-popup.service.ts index 6244d5a413ab..72ab6475a197 100644 --- a/src/main/webapp/app/exercises/shared/exercise/exercise-popup.service.ts +++ b/src/main/webapp/app/exercises/shared/exercise/exercise-popup.service.ts @@ -20,7 +20,7 @@ export class ExercisePopupService { } open(component: Component, id?: number | any, lti?: boolean | any): Promise { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { if (this.ngbModalRef != null) { resolve(this.ngbModalRef); } @@ -49,11 +49,11 @@ export class ExercisePopupService { modalRef.componentInstance.exercise = exercise; modalRef.componentInstance.ltiConfiguration = ltiConfiguration; modalRef.result.then( - (result) => { + () => { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, - (reason) => { + () => { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, diff --git a/src/main/webapp/app/exercises/shared/participation-submission/participation-submission-popup.service.ts b/src/main/webapp/app/exercises/shared/participation-submission/participation-submission-popup.service.ts index c3b3dcec1753..752d8419e990 100644 --- a/src/main/webapp/app/exercises/shared/participation-submission/participation-submission-popup.service.ts +++ b/src/main/webapp/app/exercises/shared/participation-submission/participation-submission-popup.service.ts @@ -11,7 +11,7 @@ export class ParticipationSubmissionPopupService { } open(component: Component, participationId?: number | any, submissionId?: number | any): Promise { - return new Promise((resolve, reject) => { + return new Promise((resolve) => { if (this.ngbModalRef != null) { resolve(this.ngbModalRef); } @@ -28,11 +28,11 @@ export class ParticipationSubmissionPopupService { modalRef.componentInstance.participationId = participationId; modalRef.componentInstance.submissionId = submissionId; modalRef.result.then( - (result) => { + () => { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, - (reason) => { + () => { this.router.navigate([{ outlets: { popup: null } }], { replaceUrl: true, queryParamsHandling: 'merge' }); this.ngbModalRef = null; }, diff --git a/src/main/webapp/app/exercises/shared/participation/participation.service.ts b/src/main/webapp/app/exercises/shared/participation/participation.service.ts index a9a2ea5558a6..a015c0bff179 100644 --- a/src/main/webapp/app/exercises/shared/participation/participation.service.ts +++ b/src/main/webapp/app/exercises/shared/participation/participation.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; import { SERVER_API_URL } from 'app/app.constants'; +import { map } from 'rxjs/operators'; import * as moment from 'moment'; import { createRequestOption } from 'app/shared/util/request-util'; @@ -25,19 +26,19 @@ export class ParticipationService { const copy = this.convertDateFromClient(participation); return this.http .put(this.resourceUrl, copy, { observe: 'response' }) - .map((res: EntityResponseType) => this.convertDateFromServer(res)); + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } find(participationId: number): Observable { return this.http .get(`${this.resourceUrl}/${participationId}`, { observe: 'response' }) - .map((res: EntityResponseType) => this.convertDateFromServer(res)); + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } findWithLatestResult(participationId: number): Observable { return this.http .get(`${this.resourceUrl}/${participationId}/withLatestResult`, { observe: 'response' }) - .map((res: EntityResponseType) => this.convertDateFromServer(res)); + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } /* @@ -46,12 +47,14 @@ export class ParticipationService { findParticipation(exerciseId: number): Observable { return this.http .get(SERVER_API_URL + `api/exercises/${exerciseId}/participation`, { observe: 'response' }) - .map((res: EntityResponseType) => { - if (typeof res === 'undefined' || res === null) { - return null; - } - return this.convertDateFromServer(res); - }); + .pipe( + map((res: EntityResponseType) => { + if (typeof res === 'undefined' || res === null) { + return null; + } + return this.convertDateFromServer(res); + }), + ); } findAllParticipationsByExercise(exerciseId: number, withLatestResult = false): Observable { @@ -61,7 +64,7 @@ export class ParticipationService { params: options, observe: 'response', }) - .map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res)); + .pipe(map((res: EntityArrayResponseType) => this.convertDateArrayFromServer(res))); } delete(participationId: number, req?: any): Observable> { @@ -78,18 +81,21 @@ export class ParticipationService { const copy = this.convertDateFromClient(participation); return this.http .put(`${this.resourceUrl}/${participation.id}/cleanupBuildPlan`, copy, { observe: 'response' }) - .map((res: EntityResponseType) => this.convertDateFromServer(res)); + .pipe(map((res: EntityResponseType) => this.convertDateFromServer(res))); } downloadArtifact(participationId: number) { - return this.http.get(`${this.resourceUrl}/${participationId}/buildArtifact`, { responseType: 'blob' }).map((artifact) => { - return artifact; - }); + return this.http.get(`${this.resourceUrl}/${participationId}/buildArtifact`, { responseType: 'blob' }).pipe( + map((artifact) => { + return artifact; + }), + ); } protected convertDateFromClient(participation: StudentParticipation): StudentParticipation { const copy: StudentParticipation = Object.assign({}, participation, { - initializationDate: participation.initializationDate != null && moment(participation.initializationDate).isValid() ? participation.initializationDate.toJSON() : null, + initializationDate: + participation.initializationDate != null && moment(participation.initializationDate).isValid() ? JSON.stringify(participation.initializationDate) : null, }); return copy; } diff --git a/src/main/webapp/app/exercises/shared/result/result.service.ts b/src/main/webapp/app/exercises/shared/result/result.service.ts index cfda02780697..9f5599eb27ce 100644 --- a/src/main/webapp/app/exercises/shared/result/result.service.ts +++ b/src/main/webapp/app/exercises/shared/result/result.service.ts @@ -69,10 +69,9 @@ export class ResultService implements IResultService { * Create a new example result for the provided submission ID. * * @param submissionId The ID of the example submission for which a result should get created - * @param isProgrammingExerciseWithFeedback defines if the programming exercise contains feedback * @return The newly created (and empty) example result */ - createNewExampleResult(submissionId: number, isProgrammingExerciseWithFeedback = false): Observable> { + createNewExampleResult(submissionId: number): Observable> { return this.http.post(`${this.submissionResourceUrl}/${submissionId}/example-result`, null, { observe: 'response' }); } diff --git a/src/main/webapp/app/exercises/shared/structured-grading-criterion/grading-instructions-details/grading-instructions-details.component.ts b/src/main/webapp/app/exercises/shared/structured-grading-criterion/grading-instructions-details/grading-instructions-details.component.ts index 65f1843233bd..6f49d5dfa2a5 100644 --- a/src/main/webapp/app/exercises/shared/structured-grading-criterion/grading-instructions-details/grading-instructions-details.component.ts +++ b/src/main/webapp/app/exercises/shared/structured-grading-criterion/grading-instructions-details/grading-instructions-details.component.ts @@ -156,7 +156,7 @@ export class GradingInstructionsDetailsComponent implements OnInit { } hasCriterionCommand(domainCommands: [string, DomainCommand][]): boolean { - return domainCommands.some(([text, command]) => command instanceof GradingCriterionCommand); + return domainCommands.some(([, command]) => command instanceof GradingCriterionCommand); } /** @@ -174,7 +174,7 @@ export class GradingInstructionsDetailsComponent implements OnInit { if (this.hasCriterionCommand(domainCommands) === false) { this.setParentForInstructionsWithNoCriterion(domainCommands); } else { - for (const [text, command] of domainCommands) { + for (const [, command] of domainCommands) { endOfInstructionsCommand++; if (command instanceof GradingCriterionCommand) { instructionCommands = domainCommands.slice(0, endOfInstructionsCommand - 1); @@ -198,7 +198,7 @@ export class GradingInstructionsDetailsComponent implements OnInit { * @param domainCommands containing tuples of [text, domainCommandIdentifiers] */ setParentForInstructionsWithNoCriterion(domainCommands: [string, DomainCommand][]): void { - for (const [text, command] of domainCommands) { + for (const [, command] of domainCommands) { if (command instanceof GradingInstructionCommand) { const dummyCriterion = new GradingCriterion(); const newInstruction = new GradingInstruction(); @@ -231,7 +231,7 @@ export class GradingInstructionsDetailsComponent implements OnInit { newCriterion.structuredGradingInstructions = []; const modifiedArray = domainCommands.slice(1); // remove GradingCriterionCommandIdentifier after creating its criterion object let endOfCriterion = 0; - for (const [instrText, instrCommand] of modifiedArray) { + for (const [, instrCommand] of modifiedArray) { endOfCriterion++; if (instrCommand instanceof GradingInstructionCommand) { const newInstruction = new GradingInstruction(); // create instruction objects that belong to the above created criterion @@ -245,7 +245,7 @@ export class GradingInstructionsDetailsComponent implements OnInit { } } } - this.setInstructionParameters(initialCriteriaCommands.filter(([text, command]) => command instanceof GradingCriterionCommand === false)); + this.setInstructionParameters(initialCriteriaCommands.filter(([, command]) => command instanceof GradingCriterionCommand === false)); } /** diff --git a/src/main/webapp/app/exercises/shared/team/team-exercise-search/team-exercise-search.component.ts b/src/main/webapp/app/exercises/shared/team/team-exercise-search/team-exercise-search.component.ts index 20916a5a6b34..be376fa5270b 100644 --- a/src/main/webapp/app/exercises/shared/team/team-exercise-search/team-exercise-search.component.ts +++ b/src/main/webapp/app/exercises/shared/team/team-exercise-search/team-exercise-search.component.ts @@ -79,7 +79,7 @@ export class TeamExerciseSearchComponent implements OnInit { this.searchNoResults.emit(searchTerm); } }), - map(([_, exerciseOptions]) => exerciseOptions || []), + map(([, exerciseOptions]) => exerciseOptions || []), map((exerciseOptions) => orderBy(exerciseOptions, ['releaseDate', 'id'])), ); }; diff --git a/src/main/webapp/app/exercises/shared/team/team-owner-search/team-owner-search.component.ts b/src/main/webapp/app/exercises/shared/team/team-owner-search/team-owner-search.component.ts index 0322febf9019..3fc6c568ea1f 100644 --- a/src/main/webapp/app/exercises/shared/team/team-owner-search/team-owner-search.component.ts +++ b/src/main/webapp/app/exercises/shared/team/team-owner-search/team-owner-search.component.ts @@ -91,7 +91,7 @@ export class TeamOwnerSearchComponent implements OnInit { this.searchNoResults.emit(loginOrName); } }), - map(([_, ownerOptions]) => ownerOptions || []), + map(([, ownerOptions]) => ownerOptions || []), ); }; diff --git a/src/main/webapp/app/exercises/shared/team/team-student-search/team-student-search.component.ts b/src/main/webapp/app/exercises/shared/team/team-student-search/team-student-search.component.ts index 7099ada8743e..50c2cdbe7d02 100644 --- a/src/main/webapp/app/exercises/shared/team/team-student-search/team-student-search.component.ts +++ b/src/main/webapp/app/exercises/shared/team/team-student-search/team-student-search.component.ts @@ -82,7 +82,7 @@ export class TeamStudentSearchComponent { this.searchNoResults.emit(loginOrName); } }), - map(([_, users]) => users || []), + map(([, users]) => users || []), tap((users) => { setTimeout(() => { for (let i = 0; i < this.typeaheadButtons.length; i++) { diff --git a/src/main/webapp/app/exercises/shared/team/team-update-dialog/team-delete-button.component.ts b/src/main/webapp/app/exercises/shared/team/team-update-dialog/team-delete-button.component.ts index ebe7359530e1..fbc4e4e619ff 100644 --- a/src/main/webapp/app/exercises/shared/team/team-update-dialog/team-delete-button.component.ts +++ b/src/main/webapp/app/exercises/shared/team/team-update-dialog/team-delete-button.component.ts @@ -47,6 +47,7 @@ export class TeamDeleteButtonComponent implements OnDestroy { * * @param additionalChecksValues Not used here */ + // eslint-disable-next-line @typescript-eslint/no-unused-vars removeTeam = (additionalChecksValues: { [key: string]: boolean }) => { this.teamService.delete(this.exercise, this.team.id).subscribe( () => { diff --git a/src/main/webapp/app/exercises/shared/team/team.component.html b/src/main/webapp/app/exercises/shared/team/team.component.html index 0e3cb34840f1..32ada42dd66f 100644 --- a/src/main/webapp/app/exercises/shared/team/team.component.html +++ b/src/main/webapp/app/exercises/shared/team/team.component.html @@ -42,7 +42,7 @@

[exercise]="exercise" [team]="team" [buttonSize]="ButtonSize.MEDIUM" - (delete)="onTeamDelete($event)" + (delete)="onTeamDelete()" > diff --git a/src/main/webapp/app/exercises/shared/team/team.component.ts b/src/main/webapp/app/exercises/shared/team/team.component.ts index 54d9a6591c48..4e690899f865 100644 --- a/src/main/webapp/app/exercises/shared/team/team.component.ts +++ b/src/main/webapp/app/exercises/shared/team/team.component.ts @@ -78,10 +78,8 @@ export class TeamComponent implements OnInit { * Called when the team was deleted by TeamDeleteButtonComponent * * Navigates back to the overviews of teams for the exercise. - * - * @param team Deleted team */ - onTeamDelete(team: Team) { + onTeamDelete() { this.router.navigate(['/course-management', this.exercise.course?.id, 'exercises', this.exercise.id, 'teams']); } diff --git a/src/main/webapp/app/exercises/shared/team/teams.component.ts b/src/main/webapp/app/exercises/shared/team/teams.component.ts index 9d0f90d93afb..1fe1a92031a0 100644 --- a/src/main/webapp/app/exercises/shared/team/teams.component.ts +++ b/src/main/webapp/app/exercises/shared/team/teams.component.ts @@ -1,5 +1,4 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; -import { Subscription } from 'rxjs/Subscription'; import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; import { JhiAlertService, JhiEventManager } from 'ng-jhipster'; import { ActivatedRoute } from '@angular/router'; diff --git a/src/main/webapp/app/exercises/text/assess-new/text-assessment-area/text-assessment-area.component.ts b/src/main/webapp/app/exercises/text/assess-new/text-assessment-area/text-assessment-area.component.ts index 9b424368afec..c26ce98675ba 100644 --- a/src/main/webapp/app/exercises/text/assess-new/text-assessment-area/text-assessment-area.component.ts +++ b/src/main/webapp/app/exercises/text/assess-new/text-assessment-area/text-assessment-area.component.ts @@ -1,4 +1,4 @@ -import { Component, EventEmitter, Input, Output, OnChanges, SimpleChanges } from '@angular/core'; +import { Component, EventEmitter, Input, Output, OnChanges } from '@angular/core'; import { TextSubmission } from 'app/entities/text-submission.model'; import { TextBlockRef } from 'app/entities/text-block-ref.model'; import { TextBlock } from 'app/entities/text-block.model'; @@ -28,7 +28,7 @@ export class TextAssessmentAreaComponent implements OnChanges { @Output() textBlockRefsChange = new EventEmitter(); selectedRef: TextBlockRef | null = null; - ngOnChanges(changes: SimpleChanges): void { + ngOnChanges(): void { this.textBlockRefs.sort((a, b) => a.block.startIndex - b.block.startIndex); } diff --git a/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.component.ts b/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.component.ts index dbe5c5bdb4c4..48f05bc45d44 100644 --- a/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.component.ts +++ b/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.component.ts @@ -10,7 +10,7 @@ import { StudentParticipation } from 'app/entities/participation/student-partici import { TextSubmission } from 'app/entities/text-submission.model'; import { TextExercise } from 'app/entities/text-exercise.model'; import { Result } from 'app/entities/result.model'; -import { Complaint, ComplaintType } from 'app/entities/complaint.model'; +import { Complaint } from 'app/entities/complaint.model'; import { ComplaintResponse } from 'app/entities/complaint-response.model'; import { ComplaintService } from 'app/complaints/complaint.service'; import { TextAssessmentsService } from 'app/exercises/text/assess/text-assessments.service'; diff --git a/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.route.ts b/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.route.ts index 43a52c624769..42ee44902457 100644 --- a/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.route.ts +++ b/src/main/webapp/app/exercises/text/assess-new/text-submission-assessment.route.ts @@ -1,5 +1,5 @@ import { Injectable } from '@angular/core'; -import { Routes, Resolve, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router'; +import { Routes, Resolve, ActivatedRouteSnapshot } from '@angular/router'; import { Location } from '@angular/common'; import { Observable } from 'rxjs'; @@ -16,9 +16,8 @@ export class StudentParticipationResolver implements Resolve) => { + () => { this.jhiAlertService.success('artemisApp.exampleSubmission.assessScore.success'); }, (error: HttpErrorResponse) => { @@ -373,7 +372,7 @@ export class ExampleTextSubmissionComponent implements OnInit, AfterViewInit { } readAndUnderstood() { - this.tutorParticipationService.assessExampleSubmission(this.exampleSubmission, this.exerciseId).subscribe((res: HttpResponse) => { + this.tutorParticipationService.assessExampleSubmission(this.exampleSubmission, this.exerciseId).subscribe(() => { this.jhiAlertService.success('artemisApp.exampleSubmission.readSuccessfully'); this.back(); }); diff --git a/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise-update.component.ts b/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise-update.component.ts index 10a17576f215..12792e8c58ca 100644 --- a/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise-update.component.ts +++ b/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise-update.component.ts @@ -128,12 +128,12 @@ export class TextExerciseUpdateComponent implements OnInit { private subscribeToSaveResponse(result: Observable>) { result.subscribe( - (res: HttpResponse) => this.onSaveSuccess(res.body!), + () => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError(res), ); } - private onSaveSuccess(result: TextExercise) { + private onSaveSuccess() { this.eventManager.broadcast({ name: 'textExerciseListModification', content: 'OK' }); this.isSaving = false; this.previousState(); diff --git a/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise.route.ts b/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise.route.ts index 489da246521b..1e61012ec190 100644 --- a/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise.route.ts +++ b/src/main/webapp/app/exercises/text/manage/text-exercise/text-exercise.route.ts @@ -1,4 +1,4 @@ -import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { TextExerciseComponent } from './text-exercise.component'; @@ -20,9 +20,8 @@ export class TextExerciseResolver implements Resolve { /** * Resolves the route and initializes text exercise * @param route - * @param state */ - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { + resolve(route: ActivatedRouteSnapshot) { if (route.params['exerciseId']) { return this.textExerciseService.find(route.params['exerciseId']).pipe( filter((res) => !!res.body), diff --git a/src/main/webapp/app/exercises/text/participate/text-editor.component.ts b/src/main/webapp/app/exercises/text/participate/text-editor.component.ts index e36b61b8b9d8..58351ea370c2 100644 --- a/src/main/webapp/app/exercises/text/participate/text-editor.component.ts +++ b/src/main/webapp/app/exercises/text/participate/text-editor.component.ts @@ -204,7 +204,7 @@ export class TextEditorComponent implements OnInit, OnDestroy, ComponentCanDeact this.jhiAlertService.warning('entity.action.submitDeadlineMissedAlert'); } }, - (err) => { + () => { this.jhiAlertService.error('artemisApp.modelingEditor.error'); this.submission.submitted = false; this.isSaving = false; diff --git a/src/main/webapp/app/exercises/text/participate/text-submission.service.ts b/src/main/webapp/app/exercises/text/participate/text-submission.service.ts index 3dbf16ad9991..d81121ecd2fd 100644 --- a/src/main/webapp/app/exercises/text/participate/text-submission.service.ts +++ b/src/main/webapp/app/exercises/text/participate/text-submission.service.ts @@ -1,7 +1,7 @@ import { Injectable } from '@angular/core'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs/Observable'; -import { tap } from 'rxjs/operators'; +import { tap, map } from 'rxjs/operators'; import { TextSubmission } from 'app/entities/text-submission.model'; import { createRequestOption } from 'app/shared/util/request-util'; @@ -19,7 +19,7 @@ export class TextSubmissionService { .post(`api/exercises/${exerciseId}/text-submissions`, copy, { observe: 'response', }) - .map((res: EntityResponseType) => TextSubmissionService.convertResponse(res)); + .pipe(map((res: EntityResponseType) => TextSubmissionService.convertResponse(res))); } update(textSubmission: TextSubmission, exerciseId: number): Observable { @@ -29,7 +29,7 @@ export class TextSubmissionService { headers: { 'Content-Type': 'application/json' }, observe: 'response', }) - .map((res: EntityResponseType) => TextSubmissionService.convertResponse(res)); + .pipe(map((res: EntityResponseType) => TextSubmissionService.convertResponse(res))); } getTextSubmissionsForExercise(exerciseId: number, req: { submittedOnly?: boolean; assessedByTutor?: boolean }): Observable> { @@ -39,7 +39,7 @@ export class TextSubmissionService { params: options, observe: 'response', }) - .map((res: HttpResponse) => TextSubmissionService.convertArrayResponse(res)); + .pipe(map((res: HttpResponse) => TextSubmissionService.convertArrayResponse(res))); } getTextSubmissionForExerciseWithoutAssessment(exerciseId: number, lock = false): Observable { diff --git a/src/main/webapp/app/guided-tour/guided-tour.component.ts b/src/main/webapp/app/guided-tour/guided-tour.component.ts index ef2f75ca9f74..f50ede6057c7 100644 --- a/src/main/webapp/app/guided-tour/guided-tour.component.ts +++ b/src/main/webapp/app/guided-tour/guided-tour.component.ts @@ -4,7 +4,7 @@ import { take, tap } from 'rxjs/internal/operators'; import { Direction, Orientation, OverlayPosition, UserInteractionEvent } from './guided-tour.constants'; import { GuidedTourService } from './guided-tour.service'; import { AccountService } from 'app/core/auth/account.service'; -import { ImageTourStep, TextTourStep, TourStep, VideoTourStep } from 'app/guided-tour/guided-tour-step.model'; +import { ImageTourStep, TextTourStep, VideoTourStep } from 'app/guided-tour/guided-tour-step.model'; import { cancelTour, completedTour } from 'app/guided-tour/tours/general-tour'; import { calculateLeftOffset, calculateTopOffset, isElementInViewPortHorizontally } from 'app/guided-tour/guided-tour.utils'; @@ -682,7 +682,7 @@ export class GuidedTourComponent implements AfterViewInit, OnDestroy { this.guidedTourService .observeMutations(alertElement, { childList: true }) .pipe(take(1)) - .subscribe((mutation) => { + .subscribe(() => { if (this.getSelectedElement()) { this.scrollToAndSetElement(); } diff --git a/src/main/webapp/app/guided-tour/guided-tour.service.ts b/src/main/webapp/app/guided-tour/guided-tour.service.ts index bca5d470f36e..3c47049ec4f2 100644 --- a/src/main/webapp/app/guided-tour/guided-tour.service.ts +++ b/src/main/webapp/app/guided-tour/guided-tour.service.ts @@ -649,7 +649,7 @@ export class GuidedTourService { mutation.addedNodes.length !== mutation.removedNodes.length && (mutation.addedNodes.length >= 1 || mutation.removedNodes.length >= 1), ), ) - .subscribe((mutation: MutationRecord) => { + .subscribe(() => { this.enableNextStepClick(); }); } else if (userInteraction === UserInteractionEvent.MODELING) { diff --git a/src/main/webapp/app/guided-tour/tours/course-overview-tour.ts b/src/main/webapp/app/guided-tour/tours/course-overview-tour.ts index 0a2013c04194..f75395c07a04 100644 --- a/src/main/webapp/app/guided-tour/tours/course-overview-tour.ts +++ b/src/main/webapp/app/guided-tour/tours/course-overview-tour.ts @@ -1,6 +1,6 @@ -import { Orientation, ResetParticipation, UserInteractionEvent } from 'app/guided-tour/guided-tour.constants'; +import { Orientation, ResetParticipation } from 'app/guided-tour/guided-tour.constants'; import { GuidedTour } from 'app/guided-tour/guided-tour.model'; -import { ImageTourStep, TextTourStep, UserInterActionTourStep } from 'app/guided-tour/guided-tour-step.model'; +import { ImageTourStep, TextTourStep } from 'app/guided-tour/guided-tour-step.model'; /** * This constant contains the guided tour configuration and steps for the course overview page diff --git a/src/main/webapp/app/home/home.component.ts b/src/main/webapp/app/home/home.component.ts index f4ebc053e31c..041ab1fe797f 100644 --- a/src/main/webapp/app/home/home.component.ts +++ b/src/main/webapp/app/home/home.component.ts @@ -84,7 +84,7 @@ export class HomeComponent implements OnInit, AfterViewInit { } registerAuthenticationSuccess() { - this.eventManager.subscribe('authenticationSuccess', (message: string) => { + this.eventManager.subscribe('authenticationSuccess', () => { this.accountService.identity().then((user) => { this.currentUserCallback(user!); }); @@ -131,10 +131,10 @@ export class HomeComponent implements OnInit, AfterViewInit { modalRef.componentInstance.text = 'login.ide.confirmation'; modalRef.componentInstance.title = 'login.ide.title'; modalRef.result.then( - (result) => { + () => { this.javaBridge.login(this.username, this.password); }, - (reason) => {}, + () => {}, ); } }) diff --git a/src/main/webapp/app/lecture/lecture-update.component.ts b/src/main/webapp/app/lecture/lecture-update.component.ts index 400002bf5a82..31a7f2dbf024 100644 --- a/src/main/webapp/app/lecture/lecture-update.component.ts +++ b/src/main/webapp/app/lecture/lecture-update.component.ts @@ -1,6 +1,6 @@ import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; -import { HttpErrorResponse, HttpResponse } from '@angular/common/http'; +import { HttpResponse } from '@angular/common/http'; import { Observable } from 'rxjs'; import { AlertService } from 'app/core/alert/alert.service'; import { LectureService } from './lecture.service'; @@ -58,8 +58,8 @@ export class LectureUpdateComponent implements OnInit { protected subscribeToSaveResponse(result: Observable>) { result.subscribe( - (res: HttpResponse) => this.onSaveSuccess(), - (res: HttpErrorResponse) => this.onSaveError(), + () => this.onSaveSuccess(), + () => this.onSaveError(), ); } diff --git a/src/main/webapp/app/lecture/lecture.route.ts b/src/main/webapp/app/lecture/lecture.route.ts index 6b2d0cf353e6..ac26c1ba596a 100644 --- a/src/main/webapp/app/lecture/lecture.route.ts +++ b/src/main/webapp/app/lecture/lecture.route.ts @@ -1,6 +1,6 @@ import { Injectable } from '@angular/core'; import { HttpResponse } from '@angular/common/http'; -import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot, Routes } from '@angular/router'; +import { ActivatedRouteSnapshot, Resolve, Routes } from '@angular/router'; import { UserRouteAccessService } from 'app/core/auth/user-route-access-service'; import { Observable, of } from 'rxjs'; import { filter, map } from 'rxjs/operators'; @@ -15,7 +15,7 @@ import { LectureAttachmentsComponent } from 'app/lecture/lecture-attachments.com export class LectureResolve implements Resolve { constructor(private service: LectureService) {} - resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable { + resolve(route: ActivatedRouteSnapshot): Observable { const id = route.params['id'] ? route.params['id'] : null; if (id) { return this.service.find(id).pipe( diff --git a/src/main/webapp/app/overview/course-lectures/course-lecture-row.component.html b/src/main/webapp/app/overview/course-lectures/course-lecture-row.component.html index 33b327015447..e31f0ac90513 100644 --- a/src/main/webapp/app/overview/course-lectures/course-lecture-row.component.html +++ b/src/main/webapp/app/overview/course-lectures/course-lecture-row.component.html @@ -1,4 +1,4 @@ -
+
{ + this.translateSubscription = this.translateService.onLangChange.subscribe(() => { this.groupLectures(this.DUE_DATE_DESC); }); diff --git a/src/main/webapp/app/overview/course-statistics/course-statistics.component.ts b/src/main/webapp/app/overview/course-statistics/course-statistics.component.ts index 2457fc76ee2f..96cc41894a8c 100644 --- a/src/main/webapp/app/overview/course-statistics/course-statistics.component.ts +++ b/src/main/webapp/app/overview/course-statistics/course-statistics.component.ts @@ -2,10 +2,10 @@ import { Component, OnDestroy, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Subscription } from 'rxjs/Subscription'; import { HttpResponse } from '@angular/common/http'; -import { LangChangeEvent, TranslateService } from '@ngx-translate/core'; +import { TranslateService } from '@ngx-translate/core'; import { sortBy } from 'lodash'; import { Course } from 'app/entities/course.model'; -import { CourseManagementService } from '../../course/manage/course-management.service'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; import { Result } from 'app/entities/result.model'; import * as moment from 'moment'; import { Exercise, ExerciseType } from 'app/entities/exercise.model'; @@ -206,7 +206,7 @@ export class CourseStatisticsComponent implements OnInit, OnDestroy { this.groupExercisesByType(); } - this.translationSubscription = this.translateService.onLangChange.subscribe((event: LangChangeEvent) => { + this.translationSubscription = this.translateService.onLangChange.subscribe(() => { this.exerciseTitles = { quiz: { name: this.translateService.instant('artemisApp.course.quizExercises'), diff --git a/src/main/webapp/app/overview/student-questions/student-question-row.component.ts b/src/main/webapp/app/overview/student-questions/student-question-row.component.ts index f97e4cebd637..bec2871301a6 100644 --- a/src/main/webapp/app/overview/student-questions/student-question-row.component.ts +++ b/src/main/webapp/app/overview/student-questions/student-question-row.component.ts @@ -120,7 +120,7 @@ export class StudentQuestionRowComponent implements OnInit, OnDestroy { */ saveQuestion(): void { this.studentQuestion.questionText = this.studentQuestionText; - this.studentQuestionService.update(this.studentQuestion).subscribe((studentQuestionResponse: HttpResponse) => { + this.studentQuestionService.update(this.studentQuestion).subscribe(() => { this.studentQuestionText = null; this.isEditMode = false; }); @@ -130,7 +130,7 @@ export class StudentQuestionRowComponent implements OnInit, OnDestroy { * deletes the studentQuestion */ deleteQuestion(): void { - this.studentQuestionService.delete(this.studentQuestion.id).subscribe((res: HttpResponse) => { + this.studentQuestionService.delete(this.studentQuestion.id).subscribe(() => { this.interactQuestion.emit({ name: QuestionActionName.DELETE, studentQuestion: this.studentQuestion, @@ -165,7 +165,7 @@ export class StudentQuestionRowComponent implements OnInit, OnDestroy { */ saveAnswer(): void { this.selectedQuestionAnswer!.answerText = this.questionAnswerText; - this.studentQuestionAnswerService.update(this.selectedQuestionAnswer!).subscribe((studentAnswerResponse: HttpResponse) => { + this.studentQuestionAnswerService.update(this.selectedQuestionAnswer!).subscribe(() => { this.questionAnswerText = null; this.selectedQuestionAnswer = null; this.isAnswerMode = false; @@ -174,10 +174,10 @@ export class StudentQuestionRowComponent implements OnInit, OnDestroy { /** * Takes a studentAnswer and deletes it - * @param {studentQuestionAnswer} studentAnswer + * @param {StudentQuestionAnswer} studentAnswer */ deleteAnswer(studentAnswer: StudentQuestionAnswer): void { - this.studentQuestionAnswerService.delete(studentAnswer.id).subscribe((res: HttpResponse) => { + this.studentQuestionAnswerService.delete(studentAnswer.id).subscribe(() => { this.studentQuestion.answers = this.studentQuestion.answers.filter((el) => el.id !== studentAnswer.id); this.sortQuestionAnswers(); }); @@ -185,11 +185,11 @@ export class StudentQuestionRowComponent implements OnInit, OnDestroy { /** * Takes a studentAnswer and toggles the tutorApproved field - * @param {studentQuestionAnswer} studentAnswer + * @param {StudentQuestionAnswer} studentAnswer */ toggleAnswerTutorApproved(studentAnswer: StudentQuestionAnswer): void { studentAnswer.tutorApproved = !studentAnswer.tutorApproved; - this.studentQuestionAnswerService.update(studentAnswer).subscribe((studentAnswerResponse: HttpResponse) => { + this.studentQuestionAnswerService.update(studentAnswer).subscribe(() => { this.sortQuestionAnswers(); }); } diff --git a/src/main/webapp/app/shared/category-selector/category-selector.component.ts b/src/main/webapp/app/shared/category-selector/category-selector.component.ts index 68f1ddca5315..ab8602c01126 100644 --- a/src/main/webapp/app/shared/category-selector/category-selector.component.ts +++ b/src/main/webapp/app/shared/category-selector/category-selector.component.ts @@ -1,4 +1,4 @@ -import { Component, EventEmitter, Input, OnChanges, Output, SimpleChanges, ViewChild, ViewEncapsulation } from '@angular/core'; +import { Component, EventEmitter, Input, OnChanges, Output, ViewChild, ViewEncapsulation } from '@angular/core'; import { ExerciseCategory } from 'app/entities/exercise.model'; import { ColorSelectorComponent } from 'app/shared/color-selector/color-selector.component'; @@ -19,11 +19,12 @@ export class CategorySelectorComponent implements OnChanges { @Output() selectedCategories = new EventEmitter(); uniqueCategories: ExerciseCategory[] = []; - ngOnChanges(changes: SimpleChanges) { + ngOnChanges() { if (!this.existingCategories) { return; } this.existingCategories.forEach((category) => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars const categoryIsInArray = (el: ExerciseCategory, index: number, categories: ExerciseCategory[]): boolean => { return el.category === category.category; }; diff --git a/src/main/webapp/app/shared/components/confirm-autofocus-button.component.ts b/src/main/webapp/app/shared/components/confirm-autofocus-button.component.ts index f602d86d6a91..46877a614409 100644 --- a/src/main/webapp/app/shared/components/confirm-autofocus-button.component.ts +++ b/src/main/webapp/app/shared/components/confirm-autofocus-button.component.ts @@ -48,10 +48,10 @@ export class ConfirmAutofocusButtonComponent { modalRef.componentInstance.text = this.confirmationText; modalRef.componentInstance.title = this.confirmationTitle; modalRef.result.then( - (result) => { + () => { this.onConfirm.emit(); }, - (reason) => { + () => { this.onCancel.emit(); }, ); diff --git a/src/main/webapp/app/shared/data-table/data-table.component.ts b/src/main/webapp/app/shared/data-table/data-table.component.ts index e51559a450f5..52fe324eeb1a 100644 --- a/src/main/webapp/app/shared/data-table/data-table.component.ts +++ b/src/main/webapp/app/shared/data-table/data-table.component.ts @@ -398,7 +398,7 @@ export class DataTableComponent implements OnInit, OnChanges { * * @param entity Entity that was selected via autocomplete */ - filterAfterAutocompleteSelect = (entity: BaseEntity) => { + filterAfterAutocompleteSelect = () => { this.updateEntities(); }; diff --git a/src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts b/src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts index 8c901e5548e1..5394004784c2 100644 --- a/src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts +++ b/src/main/webapp/app/shared/date-time-picker/date-time-picker.component.ts @@ -1,7 +1,7 @@ import { Component, ElementRef, EventEmitter, forwardRef, Input, Output, ViewChild } from '@angular/core'; import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms'; -import * as moment from 'moment'; import { isMoment, Moment } from 'moment'; +import * as moment from 'moment'; @Component({ selector: 'jhi-date-time-picker', @@ -47,6 +47,7 @@ export class FormDateTimePickerComponent implements ControlValueAccessor { @Input() max: Moment; // Dates after this date are not selectable. @Output() valueChange = new EventEmitter(); + // eslint-disable-next-line @typescript-eslint/no-unused-vars _onChange = (val: Moment) => {}; valueChanged() { @@ -61,6 +62,7 @@ export class FormDateTimePickerComponent implements ControlValueAccessor { this.value = value; } } + // eslint-disable-next-line @typescript-eslint/no-unused-vars registerOnTouched(fn: any) {} registerOnChange(fn: any) { this._onChange = fn; diff --git a/src/main/webapp/app/shared/layouts/profiles/page-ribbon.component.ts b/src/main/webapp/app/shared/layouts/profiles/page-ribbon.component.ts index 9ad0d2d2059f..430b9534c2e0 100644 --- a/src/main/webapp/app/shared/layouts/profiles/page-ribbon.component.ts +++ b/src/main/webapp/app/shared/layouts/profiles/page-ribbon.component.ts @@ -28,7 +28,7 @@ export class PageRibbonComponent implements OnInit { } } }, - (reason) => {}, + () => {}, ); } } diff --git a/src/main/webapp/app/shared/markdown-editor/commands/fullscreen.command.ts b/src/main/webapp/app/shared/markdown-editor/commands/fullscreen.command.ts index 02037545c012..fc6d813d7f94 100644 --- a/src/main/webapp/app/shared/markdown-editor/commands/fullscreen.command.ts +++ b/src/main/webapp/app/shared/markdown-editor/commands/fullscreen.command.ts @@ -10,7 +10,7 @@ export class FullscreenCommand extends Command { buttonIcon = 'compress'; buttonTranslationString = 'artemisApp.markdownEditor.commands.fullscreen'; - execute(input?: string): void { + execute(): void { if (this.isFullScreen()) { this.exitFullscreen(); } else { diff --git a/src/main/webapp/app/shared/markdown-editor/commands/katex.command.ts b/src/main/webapp/app/shared/markdown-editor/commands/katex.command.ts index adc7225818ad..1389c18c72ed 100644 --- a/src/main/webapp/app/shared/markdown-editor/commands/katex.command.ts +++ b/src/main/webapp/app/shared/markdown-editor/commands/katex.command.ts @@ -8,7 +8,7 @@ import { addTextAtCursor } from 'app/shared/util/markdown-util'; export class KatexCommand extends DomainTagCommand { buttonIcon = 'equals'; buttonTranslationString = 'artemisApp.markdownEditor.commands.katex'; - execute(input?: string): void { + execute(): void { const text = `${this.getOpeningIdentifier()}e^{\\frac{1}{4} y^2}${this.getClosingIdentifier()}`; addTextAtCursor(text, this.aceEditor); } diff --git a/src/main/webapp/app/shared/pipes/format-date.pipe.ts b/src/main/webapp/app/shared/pipes/format-date.pipe.ts index 7ac527b986d0..55966408cfd5 100644 --- a/src/main/webapp/app/shared/pipes/format-date.pipe.ts +++ b/src/main/webapp/app/shared/pipes/format-date.pipe.ts @@ -5,7 +5,7 @@ import * as moment from 'moment'; name: 'formatDate', }) export class DatePipe implements PipeTransform { - transform(date: any, args?: any): any { + transform(date: any): any { if (date == null) { return 'DD MMMM YYYY, hh:mm:ss PM'; } diff --git a/src/main/webapp/app/shared/result/result-detail.component.ts b/src/main/webapp/app/shared/result/result-detail.component.ts index dbf2cd43ae2e..0317ec611947 100644 --- a/src/main/webapp/app/shared/result/result-detail.component.ts +++ b/src/main/webapp/app/shared/result/result-detail.component.ts @@ -2,7 +2,6 @@ import { Component, Input, OnInit } from '@angular/core'; import { RepositoryService } from 'app/shared/result/repository.service'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { catchError, map, switchMap, tap } from 'rxjs/operators'; -import { HttpErrorResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { BuildLogEntry, BuildLogEntryArray, BuildLogType } from 'app/entities/build-log.model'; import { Feedback } from 'app/entities/feedback.model'; @@ -51,7 +50,7 @@ export class ResultDetailComponent implements OnInit { } return of(null); }), - catchError((error: HttpErrorResponse) => { + catchError(() => { // TODO: When the server would give better error information, we could improve the UI. this.loadingFailed = true; return of(null); diff --git a/src/main/webapp/app/shared/util/security-util.ts b/src/main/webapp/app/shared/util/security-util.ts index 32108c78a8ec..ea35f2bf796e 100644 --- a/src/main/webapp/app/shared/util/security-util.ts +++ b/src/main/webapp/app/shared/util/security-util.ts @@ -1,4 +1,4 @@ -export const safeUnescape = (s: string, mode = 'text/html') => { +export const safeUnescape = (s: string) => { const parser = new DOMParser(); return parser.parseFromString(s, 'text/html').body.textContent; }; diff --git a/src/test/javascript/InlineHtmlStripStylesTransformer.js b/src/test/javascript/InlineHtmlStripStylesTransformer.js index d64599a73873..1b6b13fa462e 100644 --- a/src/test/javascript/InlineHtmlStripStylesTransformer.js +++ b/src/test/javascript/InlineHtmlStripStylesTransformer.js @@ -94,7 +94,7 @@ function factory(cs) { * Our main visitor, which will be called recursively for each node in the source file's AST * @param node The node to be visited */ - var visitor = function(node) { + var visitor = function (node) { var resultNode; // before we create a deep clone to modify, we make sure that // this is an assignment which we want to transform @@ -110,8 +110,8 @@ function factory(cs) { }; return visitor; } - return function(ctx) { - return function(sf) { + return function (ctx) { + return function (sf) { return ts.visitNode(sf, createVisitor(ctx, sf)); }; }; diff --git a/src/test/javascript/e2e/account/account.spec.ts b/src/test/javascript/e2e/account/account.spec.ts index 60512df84cbe..bf64095e682e 100644 --- a/src/test/javascript/e2e/account/account.spec.ts +++ b/src/test/javascript/e2e/account/account.spec.ts @@ -1,13 +1,12 @@ import { browser, by, element, ExpectedConditions as ec } from 'protractor'; -import { NavBarPage, SettingsPage, SignInPage } from '../page-objects/jhi-page-objects'; +import { NavBarPage, SignInPage } from '../page-objects/jhi-page-objects'; const expect = chai.expect; describe('account', function () { let navBarPage: NavBarPage; let signInPage: SignInPage; - let settingsPage: SettingsPage; beforeEach(async function () { await browser.get('/'); diff --git a/src/test/javascript/e2e/entities/course.spec.ts b/src/test/javascript/e2e/entities/course.spec.ts index 54605fad1d96..45062a5ab954 100644 --- a/src/test/javascript/e2e/entities/course.spec.ts +++ b/src/test/javascript/e2e/entities/course.spec.ts @@ -57,7 +57,7 @@ describe('course', function () { await newCoursePage.browseCourseIcon(); await newCoursePage.uploadCourseIcon(); - expect(await element(by.css('.headline jhi-secured-image img'))).to.not.be.undefined; + expect(await element(by.css('.headline jhi-secured-image img'))).to.not.equal(undefined); await newCoursePage.clickCancel(); }); diff --git a/src/test/javascript/e2e/entities/exercise-hint/exercise-hint.page-object.ts b/src/test/javascript/e2e/entities/exercise-hint/exercise-hint.page-object.ts index 87db9896cfd5..e9b549c1711c 100644 --- a/src/test/javascript/e2e/entities/exercise-hint/exercise-hint.page-object.ts +++ b/src/test/javascript/e2e/entities/exercise-hint/exercise-hint.page-object.ts @@ -5,11 +5,11 @@ export class ExerciseHintComponentsPage { deleteButtons = element.all(by.css('jhi-exercise-hint div table .btn-danger')); title = element.all(by.css('jhi-exercise-hint div h2#page-heading span')).first(); - async clickOnCreateButton(timeout?: number) { + async clickOnCreateButton() { await this.createButton.click(); } - async clickOnLastDeleteButton(timeout?: number) { + async clickOnLastDeleteButton() { await this.deleteButtons.last().click(); } @@ -50,7 +50,7 @@ export class ExerciseHintUpdatePage { return await this.contentInput.getAttribute('value'); } - async exerciseSelectLastOption(timeout?: number) { + async exerciseSelectLastOption() { await this.exerciseSelect.all(by.tagName('option')).last().click(); } @@ -66,11 +66,11 @@ export class ExerciseHintUpdatePage { return await this.exerciseSelect.element(by.css('option:checked')).getText(); } - async save(timeout?: number) { + async save() { await this.saveButton.click(); } - async cancel(timeout?: number) { + async cancel() { await this.cancelButton.click(); } @@ -87,7 +87,7 @@ export class ExerciseHintDeleteDialog { return this.dialogTitle.getAttribute('jhiTranslate'); } - async clickOnConfirmButton(timeout?: number) { + async clickOnConfirmButton() { await this.confirmButton.click(); } } diff --git a/src/test/javascript/e2e/page-objects/entities/course-page-object.ts b/src/test/javascript/e2e/page-objects/entities/course-page-object.ts index a8aa015dbe3b..a471e5a735a6 100644 --- a/src/test/javascript/e2e/page-objects/entities/course-page-object.ts +++ b/src/test/javascript/e2e/page-objects/entities/course-page-object.ts @@ -44,9 +44,9 @@ export class NewCoursePage { } async browseCourseIcon() { - let path = require('path'); - let fileToUpload = '../entities/tum-logo.png'; - let absolutePath = path.resolve(__dirname, fileToUpload); + const path = require('path'); + const fileToUpload = '../entities/tum-logo.png'; + const absolutePath = path.resolve(__dirname, fileToUpload); await this.browse.sendKeys(absolutePath); } diff --git a/src/test/javascript/e2e/quiz-exercise/quiz-exericse.spec.ts b/src/test/javascript/e2e/quiz-exercise/quiz-exericse.spec.ts index 61cfe58f3fed..48fcde731482 100644 --- a/src/test/javascript/e2e/quiz-exercise/quiz-exericse.spec.ts +++ b/src/test/javascript/e2e/quiz-exercise/quiz-exericse.spec.ts @@ -1,7 +1,6 @@ import { NavBarPage, SignInPage } from '../page-objects/jhi-page-objects'; import { browser, by, element, ExpectedConditions as ec } from 'protractor'; import { CoursePage, NewCoursePage } from '../page-objects/entities/course-page-object'; -import { QuizExercisePage } from '../page-objects/entities/quiz-exercise-page-object'; const expect = chai.expect; @@ -10,7 +9,6 @@ describe('quiz-exercise', function () { let signInPage: SignInPage; let coursePage: CoursePage; let newCoursePage: NewCoursePage; - let quizExercisePage: QuizExercisePage; let courseId: string; let quizId: string; @@ -57,11 +55,11 @@ describe('quiz-exercise', function () { // expect(createQuizButton.isPresent()); await createQuizButton.click(); - //set title of quiz + // set title of quiz const title = element(by.id('quiz-title')); title.sendKeys('test-quiz'); - //set duration of quiz + // set duration of quiz const durationMinutes = await element(by.id('quiz-duration-minutes')); durationMinutes.clear(); durationMinutes.sendKeys('0'); @@ -69,15 +67,15 @@ describe('quiz-exercise', function () { durationSeconds.clear(); durationSeconds.sendKeys('5'); - //add MC question + // add MC question const addMcButton = await element(by.id('quiz-add-mc-question')); await addMcButton.click(); // set title of mc question - const mcQuestionTitle = await element(by.id('mc-question-title')); //TODO: we need to support multiple questions + const mcQuestionTitle = await element(by.id('mc-question-title')); // TODO: we need to support multiple questions mcQuestionTitle.sendKeys('test-mc'); - //deactivate random order to make the test case deterministic + // deactivate random order to make the test case deterministic const randomOrder = await element(by.css('[for="cbRandomizeOrderMC1"]')); await randomOrder.click(); @@ -89,35 +87,35 @@ describe('quiz-exercise', function () { const backButton = await element(by.id('quiz-cancel-back-button')); expect(backButton.isPresent()); - //TODO: check that the button name is "Back" + // TODO: check that the button name is "Back" await backButton.click(); const quizRows = element.all(by.tagName('tbody')).all(by.tagName('tr')); quizId = await quizRows.last().element(by.css('td:nth-child(1) > a')).getText(); - //TODO: check that we leave the page and there is a new entry + // TODO: check that we leave the page and there is a new entry }); it('participate in quiz', async function () { - //set visible + // set visible const setVisibleButton = await element(by.id(`quiz-set-visible-${quizId}`)); expect(setVisibleButton.isPresent()); await setVisibleButton.click(); await browser.sleep(500); // let's wait shortly so that the server gets everything right with the database - //start quiz + // start quiz const startQuizInstructorButton = await element(by.id(`instructor-quiz-start-${quizId}`)); expect(startQuizInstructorButton.isPresent()); await startQuizInstructorButton.click(); await browser.sleep(500); // let's wait shortly so that the server gets everything right with the database - //navigate to courses + // navigate to courses await navBarPage.clickOnOverviewMenu(); browser.wait(ec.urlContains(`overview`), 1000).then((result: any) => expect(result).to.be.true); - //open or start quiz (depends a bit on the timing) + // open or start quiz (depends a bit on the timing) let startQuizButton = await element(by.id(`student-quiz-start-${quizId}`)); if (!startQuizButton.isPresent()) { startQuizButton = await element(by.id(`student-quiz-open-${quizId}`)); @@ -131,25 +129,25 @@ describe('quiz-exercise', function () { browser.waitForAngularEnabled(false); await browser.sleep(2000); // wait till ui is loaded - //answer quiz - //TODO the answer options are random, search for the correct and incorrect answer option before clicking in it + // answer quiz + // TODO the answer options are random, search for the correct and incorrect answer option before clicking in it const firstAnswerOption = await element(by.id(`answer-option-0`)); expect(firstAnswerOption.isPresent()); - await firstAnswerOption.click(); //select - await firstAnswerOption.click(); //deselect - await firstAnswerOption.click(); //select + await firstAnswerOption.click(); // select + await firstAnswerOption.click(); // deselect + await firstAnswerOption.click(); // select const secondAnswerOption = await element(by.id(`answer-option-1`)); expect(secondAnswerOption.isPresent()); - await secondAnswerOption.click(); //select - await secondAnswerOption.click(); //deselect + await secondAnswerOption.click(); // select + await secondAnswerOption.click(); // deselect - //submit quiz + // submit quiz const submitQuizButton = await element(by.id(`submit-quiz`)); expect(submitQuizButton.isPresent()); await submitQuizButton.click(); - //wait until the quiz has finished + // wait until the quiz has finished await expect(browser.wait(ec.visibilityOf(element(by.id('quiz-score'))), 15000)).to.become(true); await element(by.id('quiz-score-result')) @@ -163,7 +161,7 @@ describe('quiz-exercise', function () { .then((text) => { expect(text).equals('Correct'); }) - .catch((error) => { + .catch(() => { expect.fail('first answer option not found as correct'); }); @@ -172,7 +170,7 @@ describe('quiz-exercise', function () { .then((text) => { expect(text).equals('Wrong'); }) - .catch((error) => { + .catch(() => { expect.fail('second answer option not found as correct'); }); @@ -182,7 +180,7 @@ describe('quiz-exercise', function () { it('delete quiz', async function () { browser.waitForAngularEnabled(false); await browser.sleep(500); // let's wait shortly so that the server gets everything right with the database - //navigate to course administration + // navigate to course administration await navBarPage.clickOnCourseAdminMenu(); browser.wait(ec.urlContains(`course`), 1000).then((result: any) => expect(result).to.be.true); @@ -198,11 +196,11 @@ describe('quiz-exercise', function () { // expect(createQuizButton.isPresent()); await createQuizButton.click(); - //set title of SA quiz + // set title of SA quiz const title = element(by.id('quiz-title')); title.sendKeys('test-SA-quiz'); - //set duration of quiz + // set duration of quiz const durationMinutes = await element(by.id('quiz-duration-minutes')); durationMinutes.clear(); durationMinutes.sendKeys('0'); @@ -210,12 +208,12 @@ describe('quiz-exercise', function () { durationSeconds.clear(); durationSeconds.sendKeys('5'); - //add short answer question + // add short answer question const addShortAnswerButton = await element(by.id('quiz-add-short-answer-question')); await addShortAnswerButton.click(); // set title of short answer question - const shortAnswerQuestionTitle = await element(by.id('short-answer-question-title')); //TODO: we need to support multiple questions + const shortAnswerQuestionTitle = await element(by.id('short-answer-question-title')); // TODO: we need to support multiple questions shortAnswerQuestionTitle.sendKeys('test-short-answer'); const quizSaveButton = await element(by.id('quiz-save')); @@ -226,16 +224,16 @@ describe('quiz-exercise', function () { const backButton = await element(by.id('quiz-cancel-back-button')); expect(backButton.isPresent()); - //TODO: check that the button name is "Back" + // TODO: check that the button name is "Back" await backButton.click(); await browser .switchTo() .alert() .then((alert: any) => alert.accept()) - .catch((reason: any) => expect.fail('Did not show Alert on unsaed changes!')); + .catch(() => expect.fail('Did not show Alert on unsaved changes!')); - //TODO: check that we leave the page and there is a new entry + // TODO: check that we leave the page and there is a new entry }); after(async function () { @@ -245,7 +243,7 @@ describe('quiz-exercise', function () { await navBarPage.clickOnCourseAdminMenu(); browser.waitForAngularEnabled(true); - //Delete course + // Delete course let rows = element.all(by.tagName('tbody')).all(by.tagName('tr')); const numberOfCourses = await rows.count(); diff --git a/src/test/javascript/jest.config.js b/src/test/javascript/jest.config.js index 5eb8184d5ac6..7bb43e378ca6 100644 --- a/src/test/javascript/jest.config.js +++ b/src/test/javascript/jest.config.js @@ -13,7 +13,12 @@ module.exports = { modulePaths: ['/src/main/webapp/'], transformIgnorePatterns: [`/node_modules/(?!${esModules})`], rootDir: '../../../', - testMatch: ['/src/test/javascript/spec/integration/**/*.ts', '/src/test/javascript/spec/component/**/*.ts', '/src/test/javascript/spec/service/**/*.ts'], + testMatch: [ + '/src/test/javascript/spec/component/**/*.ts', + '/src/test/javascript/spec/directive/**/*.ts', + '/src/test/javascript/spec/integration/**/*.ts', + '/src/test/javascript/spec/service/**/*.ts', + ], moduleNameMapper: { '^app/(.*)': '/src/main/webapp/app/$1', 'test/(.*)': '/src/test/javascript/spec/$1', diff --git a/src/test/javascript/protractor.conf.js b/src/test/javascript/protractor.conf.js index a1019b701157..bae7fcab1f8f 100644 --- a/src/test/javascript/protractor.conf.js +++ b/src/test/javascript/protractor.conf.js @@ -1,4 +1,3 @@ - exports.config = { allScriptsTimeout: 20000, @@ -11,9 +10,9 @@ exports.config = { browserName: 'chrome', chromeOptions: { args: process.env.JHI_E2E_HEADLESS - ? [ "--headless", "--disable-gpu", "--window-size=1280,1024", "--disable-extensions", "incognito" ] - : [ "--disable-gpu", "--window-size=1280,1024", "--disable-extensions", "incognito" ] - } + ? ['--headless', '--disable-gpu', '--window-size=1280,1024', '--disable-extensions', 'incognito'] + : ['--disable-gpu', '--window-size=1280,1024', '--disable-extensions', 'incognito'], + }, }, directConnect: true, @@ -28,17 +27,17 @@ exports.config = { reporter: 'spec', slow: 3000, ui: 'bdd', - timeout: 720000 + timeout: 720000, }, - beforeLaunch: function() { + beforeLaunch: function () { require('ts-node').register({ - project: 'tsconfig.e2e.json' + project: 'tsconfig.e2e.json', }); }, - onPrepare: function() { - browser.driver.manage().window().setRect({x: 100, y: 100, width: 1280, height: 1024}); + onPrepare: function () { + browser.driver.manage().window().setRect({ x: 100, y: 100, width: 1280, height: 1024 }); // Disable animations // @ts-ignore browser.executeScript('document.body.className += " notransition";'); @@ -51,5 +50,5 @@ exports.config = { global.chai = chai; }, - useAllAngular2AppRoots: true + useAllAngular2AppRoots: true, }; diff --git a/src/test/javascript/spec/app/account/activate/activate.component.spec.ts b/src/test/javascript/spec/app/account/activate/activate.component.spec.ts deleted file mode 100644 index 30d142b11312..000000000000 --- a/src/test/javascript/spec/app/account/activate/activate.component.spec.ts +++ /dev/null @@ -1,72 +0,0 @@ -import { async, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of, throwError } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { MockActivatedRoute } from '../../../helpers/mock-route.service'; -import { ActivateService } from 'app/account/activate/activate.service'; -import { ActivateComponent } from 'app/account/activate/activate.component'; - -describe('Component Tests', () => { - describe('ActivateComponent', () => { - let comp: ActivateComponent; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ActivateComponent], - providers: [ - { - provide: ActivatedRoute, - useValue: new MockActivatedRoute({ key: 'ABC123' }), - }, - ], - }) - .overrideTemplate(ActivateComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - const fixture = TestBed.createComponent(ActivateComponent); - comp = fixture.componentInstance; - }); - - it('calls activate.get with the key from params', inject( - [ActivateService], - fakeAsync((service: ActivateService) => { - spyOn(service, 'get').and.returnValue(of()); - - comp.ngOnInit(); - tick(); - - expect(service.get).toHaveBeenCalledWith('ABC123'); - }), - )); - - it('should set set success to OK upon successful activation', inject( - [ActivateService], - fakeAsync((service: ActivateService) => { - spyOn(service, 'get').and.returnValue(of({})); - - comp.ngOnInit(); - tick(); - - expect(comp.error).toBe(null); - expect(comp.success).toEqual('OK'); - }), - )); - - it('should set set error to ERROR upon activation failure', inject( - [ActivateService], - fakeAsync((service: ActivateService) => { - spyOn(service, 'get').and.returnValue(throwError('ERROR')); - - comp.ngOnInit(); - tick(); - - expect(comp.error).toBe('ERROR'); - expect(comp.success).toEqual(null); - }), - )); - }); -}); diff --git a/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts b/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts deleted file mode 100644 index aa13f52f56d8..000000000000 --- a/src/test/javascript/spec/app/account/password-reset/finish/password-reset-finish.component.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { of, throwError } from 'rxjs'; -import { ElementRef, Renderer2 } from '@angular/core'; -import { ActivatedRoute } from '@angular/router'; - -import { ArtemisTestModule } from '../../../../test.module'; -import { PasswordResetFinishComponent } from 'app/account/password-reset/finish/password-reset-finish.component'; -import { PasswordResetFinishService } from 'app/account/password-reset/finish/password-reset-finish.service'; -import { MockActivatedRoute } from '../../../../helpers/mock-route.service'; - -describe('Component Tests', () => { - describe('PasswordResetFinishComponent', () => { - let fixture: ComponentFixture; - let comp: PasswordResetFinishComponent; - - beforeEach(() => { - fixture = TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [PasswordResetFinishComponent], - providers: [ - { - provide: ActivatedRoute, - useValue: new MockActivatedRoute({ key: 'XYZPDQ' }), - }, - { - provide: Renderer2, - useValue: { - invokeElementMethod(renderElement: any, methodName: string, args?: any[]) {}, - }, - }, - { - provide: ElementRef, - useValue: new ElementRef(null), - }, - ], - }) - .overrideTemplate(PasswordResetFinishComponent, '') - .createComponent(PasswordResetFinishComponent); - }); - - beforeEach(() => { - fixture = TestBed.createComponent(PasswordResetFinishComponent); - comp = fixture.componentInstance; - comp.ngOnInit(); - }); - - it('should define its initial state', () => { - comp.ngOnInit(); - - expect(comp.keyMissing).toBeFalsy(); - expect(comp.key).toEqual('XYZPDQ'); - expect(comp.resetAccount).toEqual({}); - }); - - it('sets focus after the view has been initialized', inject([ElementRef], (elementRef: ElementRef) => { - const element = fixture.nativeElement; - const node = { - focus() {}, - }; - - elementRef.nativeElement = element; - spyOn(element, 'querySelector').and.returnValue(node); - spyOn(node, 'focus'); - - comp.ngAfterViewInit(); - - expect(element.querySelector).toHaveBeenCalledWith('#password'); - expect(node.focus).toHaveBeenCalled(); - })); - - it('should ensure the two passwords entered match', () => { - comp.resetAccount.password = 'password'; - comp.confirmPassword = 'non-matching'; - - comp.finishReset(); - - expect(comp.doNotMatch).toEqual('ERROR'); - }); - - it('should update success to OK after resetting password', inject( - [PasswordResetFinishService], - fakeAsync((service: PasswordResetFinishService) => { - spyOn(service, 'save').and.returnValue(of({})); - - comp.resetAccount.password = 'password'; - comp.confirmPassword = 'password'; - - comp.finishReset(); - tick(); - - expect(service.save).toHaveBeenCalledWith({ - key: 'XYZPDQ', - newPassword: 'password', - }); - expect(comp.success).toEqual('OK'); - }), - )); - - it('should notify of generic error', inject( - [PasswordResetFinishService], - fakeAsync((service: PasswordResetFinishService) => { - spyOn(service, 'save').and.returnValue(throwError('ERROR')); - - comp.resetAccount.password = 'password'; - comp.confirmPassword = 'password'; - - comp.finishReset(); - tick(); - - expect(service.save).toHaveBeenCalledWith({ - key: 'XYZPDQ', - newPassword: 'password', - }); - expect(comp.success).toBeNull(); - expect(comp.error).toEqual('ERROR'); - }), - )); - }); -}); diff --git a/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts b/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts deleted file mode 100644 index 322000a79ca0..000000000000 --- a/src/test/javascript/spec/app/account/password-reset/init/password-reset-init.component.spec.ts +++ /dev/null @@ -1,107 +0,0 @@ -import { ComponentFixture, inject, TestBed } from '@angular/core/testing'; -import { ElementRef, Renderer2 } from '@angular/core'; -import { of, throwError } from 'rxjs'; - -import { ArtemisTestModule } from '../../../../test.module'; -import { PasswordResetInitComponent } from 'app/account/password-reset/init/password-reset-init.component'; -import { PasswordResetInitService } from 'app/account/password-reset/init/password-reset-init.service'; -import { EMAIL_NOT_FOUND_TYPE } from 'app/shared'; - -describe('Component Tests', () => { - describe('PasswordResetInitComponent', () => { - let fixture: ComponentFixture; - let comp: PasswordResetInitComponent; - - beforeEach(() => { - fixture = TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [PasswordResetInitComponent], - providers: [ - { - provide: Renderer2, - useValue: { - invokeElementMethod(renderElement: any, methodName: string, args?: any[]) {}, - }, - }, - { - provide: ElementRef, - useValue: new ElementRef(null), - }, - ], - }) - .overrideTemplate(PasswordResetInitComponent, '') - .createComponent(PasswordResetInitComponent); - comp = fixture.componentInstance; - comp.ngOnInit(); - }); - - it('should define its initial state', () => { - expect(comp.success).toBeUndefined(); - expect(comp.error).toBeUndefined(); - expect(comp.errorEmailNotExists).toBeUndefined(); - expect(comp.resetAccount).toEqual({}); - }); - - it('sets focus after the view has been initialized', inject([ElementRef], (elementRef: ElementRef) => { - const element = fixture.nativeElement; - const node = { - focus() {}, - }; - - elementRef.nativeElement = element; - spyOn(element, 'querySelector').and.returnValue(node); - spyOn(node, 'focus'); - - comp.ngAfterViewInit(); - - expect(element.querySelector).toHaveBeenCalledWith('#email'); - expect(node.focus).toHaveBeenCalled(); - })); - - it('notifies of success upon successful requestReset', inject([PasswordResetInitService], (service: PasswordResetInitService) => { - spyOn(service, 'save').and.returnValue(of({})); - comp.resetAccount.email = 'user@domain.com'; - - comp.requestReset(); - - expect(service.save).toHaveBeenCalledWith('user@domain.com'); - expect(comp.success).toEqual('OK'); - expect(comp.error).toBeNull(); - expect(comp.errorEmailNotExists).toBeNull(); - })); - - it('notifies of unknown email upon email address not registered/400', inject([PasswordResetInitService], (service: PasswordResetInitService) => { - spyOn(service, 'save').and.returnValue( - throwError({ - status: 400, - error: { type: EMAIL_NOT_FOUND_TYPE }, - }), - ); - comp.resetAccount.email = 'user@domain.com'; - - comp.requestReset(); - - expect(service.save).toHaveBeenCalledWith('user@domain.com'); - expect(comp.success).toBeNull(); - expect(comp.error).toBeNull(); - expect(comp.errorEmailNotExists).toEqual('ERROR'); - })); - - it('notifies of error upon error response', inject([PasswordResetInitService], (service: PasswordResetInitService) => { - spyOn(service, 'save').and.returnValue( - throwError({ - status: 503, - data: 'something else', - }), - ); - comp.resetAccount.email = 'user@domain.com'; - - comp.requestReset(); - - expect(service.save).toHaveBeenCalledWith('user@domain.com'); - expect(comp.success).toBeNull(); - expect(comp.errorEmailNotExists).toBeNull(); - expect(comp.error).toEqual('ERROR'); - })); - }); -}); diff --git a/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts b/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts deleted file mode 100644 index 73b3f0f5ffbf..000000000000 --- a/src/test/javascript/spec/app/account/password/password-strength-bar.component.spec.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; - -import { PasswordStrengthBarComponent } from 'app/account/password/password-strength-bar.component'; - -describe('Component Tests', () => { - describe('PasswordStrengthBarComponent', () => { - let comp: PasswordStrengthBarComponent; - let fixture: ComponentFixture; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - declarations: [PasswordStrengthBarComponent], - }) - .overrideTemplate(PasswordStrengthBarComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(PasswordStrengthBarComponent); - comp = fixture.componentInstance; - }); - - describe('PasswordStrengthBarComponents', () => { - it('should initialize with default values', () => { - expect(comp.measureStrength('')).toBe(0); - expect(comp.colors).toEqual(['#F00', '#F90', '#FF0', '#9F0', '#0F0']); - expect(comp.getColor(0).idx).toBe(1); - expect(comp.getColor(0).col).toBe(comp.colors[0]); - }); - - it('should increase strength upon password value change', () => { - expect(comp.measureStrength('')).toBe(0); - expect(comp.measureStrength('aa')).toBeGreaterThanOrEqual(comp.measureStrength('')); - expect(comp.measureStrength('aa^6')).toBeGreaterThanOrEqual(comp.measureStrength('aa')); - expect(comp.measureStrength('Aa090(**)')).toBeGreaterThanOrEqual(comp.measureStrength('aa^6')); - expect(comp.measureStrength('Aa090(**)+-07365')).toBeGreaterThanOrEqual(comp.measureStrength('Aa090(**)')); - }); - - it('should change the color based on strength', () => { - expect(comp.getColor(0).col).toBe(comp.colors[0]); - expect(comp.getColor(11).col).toBe(comp.colors[1]); - expect(comp.getColor(22).col).toBe(comp.colors[2]); - expect(comp.getColor(33).col).toBe(comp.colors[3]); - expect(comp.getColor(44).col).toBe(comp.colors[4]); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/account/password/password.component.spec.ts b/src/test/javascript/spec/app/account/password/password.component.spec.ts deleted file mode 100644 index d3198c660b17..000000000000 --- a/src/test/javascript/spec/app/account/password/password.component.spec.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of, throwError } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { PasswordComponent } from 'app/account/password/password.component'; -import { PasswordService } from 'app/account/password/password.service'; -import { MockTrackerService } from '../../../helpers/mock-tracker.service'; - -describe('Component Tests', () => { - describe('PasswordComponent', () => { - let comp: PasswordComponent; - let fixture: ComponentFixture; - let service: PasswordService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [PasswordComponent], - providers: [ - { - provide: JhiTrackerService, - useClass: MockTrackerService, - }, - ], - }) - .overrideTemplate(PasswordComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(PasswordComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(PasswordService); - }); - - it('should show error if passwords do not match', () => { - // GIVEN - comp.newPassword = 'password1'; - comp.confirmPassword = 'password2'; - // WHEN - comp.changePassword(); - // THEN - expect(comp.doNotMatch).toBe('ERROR'); - expect(comp.error).toBeNull(); - expect(comp.success).toBeNull(); - }); - - it('should call Auth.changePassword when passwords match', () => { - // GIVEN - const passwordValues = { - currentPassword: 'oldPassword', - newPassword: 'myPassword', - }; - - spyOn(service, 'save').and.returnValue(of(new HttpResponse({ body: true }))); - comp.currentPassword = passwordValues.currentPassword; - comp.newPassword = comp.confirmPassword = passwordValues.newPassword; - - // WHEN - comp.changePassword(); - - // THEN - expect(service.save).toHaveBeenCalledWith(passwordValues.newPassword, passwordValues.currentPassword); - }); - - it('should set success to OK upon success', function () { - // GIVEN - spyOn(service, 'save').and.returnValue(of(new HttpResponse({ body: true }))); - comp.newPassword = comp.confirmPassword = 'myPassword'; - - // WHEN - comp.changePassword(); - - // THEN - expect(comp.doNotMatch).toBeNull(); - expect(comp.error).toBeNull(); - expect(comp.success).toBe('OK'); - }); - - it('should notify of error if change password fails', function () { - // GIVEN - spyOn(service, 'save').and.returnValue(throwError('ERROR')); - comp.newPassword = comp.confirmPassword = 'myPassword'; - - // WHEN - comp.changePassword(); - - // THEN - expect(comp.doNotMatch).toBeNull(); - expect(comp.success).toBeNull(); - expect(comp.error).toBe('ERROR'); - }); - }); -}); diff --git a/src/test/javascript/spec/app/account/register/register.component.spec.ts b/src/test/javascript/spec/app/account/register/register.component.spec.ts deleted file mode 100644 index 5e814523e211..000000000000 --- a/src/test/javascript/spec/app/account/register/register.component.spec.ts +++ /dev/null @@ -1,121 +0,0 @@ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { of, throwError } from 'rxjs'; - -import { JhiLanguageService } from 'ng-jhipster'; -import { MockLanguageService } from '../../../helpers/mock-language.service'; -import { ArtemisTestModule } from '../../../test.module'; -import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/shared'; -import { RegisterService } from 'app/account/register/register.service'; -import { RegisterComponent } from 'app/account/register/register.component'; - -describe('Component Tests', () => { - describe('RegisterComponent', () => { - let fixture: ComponentFixture; - let comp: RegisterComponent; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [RegisterComponent], - }) - .overrideTemplate(RegisterComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(RegisterComponent); - comp = fixture.componentInstance; - comp.ngOnInit(); - }); - - it('should ensure the two passwords entered match', () => { - comp.registerAccount.password = 'password'; - comp.confirmPassword = 'non-matching'; - - comp.register(); - - expect(comp.doNotMatch).toEqual('ERROR'); - }); - - it('should update success to OK after creating an account', inject( - [RegisterService, JhiLanguageService], - fakeAsync((service: RegisterService, mockTranslate: MockLanguageService) => { - spyOn(service, 'save').and.returnValue(of({})); - comp.registerAccount.password = comp.confirmPassword = 'password'; - - comp.register(); - tick(); - - expect(service.save).toHaveBeenCalledWith({ - password: 'password', - langKey: 'en', - }); - expect(comp.success).toEqual(true); - expect(comp.registerAccount.langKey).toEqual('en'); - expect(mockTranslate.getCurrentSpy).toHaveBeenCalled(); - expect(comp.errorUserExists).toBeNull(); - expect(comp.errorEmailExists).toBeNull(); - expect(comp.error).toBeNull(); - }), - )); - - it('should notify of user existence upon 400/login already in use', inject( - [RegisterService], - fakeAsync((service: RegisterService) => { - spyOn(service, 'save').and.returnValue( - throwError({ - status: 400, - error: { type: LOGIN_ALREADY_USED_TYPE }, - }), - ); - comp.registerAccount.password = comp.confirmPassword = 'password'; - - comp.register(); - tick(); - - expect(comp.errorUserExists).toEqual('ERROR'); - expect(comp.errorEmailExists).toBeNull(); - expect(comp.error).toBeNull(); - }), - )); - - it('should notify of email existence upon 400/email address already in use', inject( - [RegisterService], - fakeAsync((service: RegisterService) => { - spyOn(service, 'save').and.returnValue( - throwError({ - status: 400, - error: { type: EMAIL_ALREADY_USED_TYPE }, - }), - ); - comp.registerAccount.password = comp.confirmPassword = 'password'; - - comp.register(); - tick(); - - expect(comp.errorEmailExists).toEqual('ERROR'); - expect(comp.errorUserExists).toBeNull(); - expect(comp.error).toBeNull(); - }), - )); - - it('should notify of generic error', inject( - [RegisterService], - fakeAsync((service: RegisterService) => { - spyOn(service, 'save').and.returnValue( - throwError({ - status: 503, - }), - ); - comp.registerAccount.password = comp.confirmPassword = 'password'; - - comp.register(); - tick(); - - expect(comp.errorUserExists).toBeNull(); - expect(comp.errorEmailExists).toBeNull(); - expect(comp.error).toEqual('ERROR'); - }), - )); - }); -}); diff --git a/src/test/javascript/spec/app/account/settings/settings.component.spec.ts b/src/test/javascript/spec/app/account/settings/settings.component.spec.ts deleted file mode 100644 index 6ee20eb1d03c..000000000000 --- a/src/test/javascript/spec/app/account/settings/settings.component.spec.ts +++ /dev/null @@ -1,91 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { throwError } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { Principal } from 'app/core'; -import { AccountService } from 'app/core/auth/account.service'; -import { SettingsComponent } from 'app/account/settings/settings.component'; -import { JhiTrackerService } from 'app/core/tracker/tracker.service'; -import { MockTrackerService } from '../../../helpers/mock-tracker.service'; - -describe('Component Tests', () => { - describe('SettingsComponent', () => { - let comp: SettingsComponent; - let fixture: ComponentFixture; - let mockAuth: any; - let mockPrincipal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [SettingsComponent], - providers: [ - { - provide: JhiTrackerService, - useClass: MockTrackerService, - }, - ], - }) - .overrideTemplate(SettingsComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(SettingsComponent); - comp = fixture.componentInstance; - mockAuth = fixture.debugElement.injector.get(AccountService); - mockPrincipal = fixture.debugElement.injector.get(Principal); - }); - - it('should send the current identity upon save', () => { - // GIVEN - const accountValues = { - firstName: 'John', - lastName: 'Doe', - - activated: true, - email: 'john.doe@mail.com', - langKey: 'en', - login: 'john', - }; - mockPrincipal.setResponse(accountValues); - - // WHEN - comp.settingsAccount = accountValues; - comp.save(); - - // THEN - expect(mockPrincipal.identitySpy).toHaveBeenCalled(); - expect(mockAuth.saveSpy).toHaveBeenCalledWith(accountValues); - expect(comp.settingsAccount).toEqual(accountValues); - }); - - it('should notify of success upon successful save', () => { - // GIVEN - const accountValues = { - firstName: 'John', - lastName: 'Doe', - }; - mockPrincipal.setResponse(accountValues); - - // WHEN - comp.save(); - - // THEN - expect(comp.error).toBeNull(); - expect(comp.success).toBe('OK'); - }); - - it('should notify of error upon failed save', () => { - // GIVEN - mockAuth.saveSpy.and.returnValue(throwError('ERROR')); - - // WHEN - comp.save(); - - // THEN - expect(comp.error).toEqual('ERROR'); - expect(comp.success).toBeNull(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts b/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts deleted file mode 100644 index cec00e27bd92..000000000000 --- a/src/test/javascript/spec/app/admin/audits/audits.component.spec.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { AuditsComponent } from 'app/admin/audits/audits.component'; -import { AuditsService } from 'app/admin/audits/audits.service'; -import { Audit } from 'app/admin/audits/audit.model'; -import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; - -function build2DigitsDatePart(datePart: number) { - return `0${datePart}`.slice(-2); -} - -function getDate(isToday = true) { - let date: Date = new Date(); - if (isToday) { - // Today + 1 day - needed if the current day must be included - date.setDate(date.getDate() + 1); - } else { - // get last month - if (date.getMonth() === 0) { - date = new Date(date.getFullYear() - 1, 11, date.getDate()); - } else { - date = new Date(date.getFullYear(), date.getMonth() - 1, date.getDate()); - } - } - const monthString = build2DigitsDatePart(date.getMonth() + 1); - const dateString = build2DigitsDatePart(date.getDate()); - return `${date.getFullYear()}-${monthString}-${dateString}`; -} - -describe('Component Tests', () => { - describe('AuditsComponent', () => { - let comp: AuditsComponent; - let fixture: ComponentFixture; - let service: AuditsService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [AuditsComponent], - providers: [AuditsService], - }) - .overrideTemplate(AuditsComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(AuditsComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(AuditsService); - }); - - describe('today function ', () => { - it('should set toDate to current date', () => { - comp.today(); - expect(comp.toDate).toBe(getDate()); - }); - }); - - describe('previousMonth function ', () => { - it('should set fromDate to current date', () => { - comp.previousMonth(); - expect(comp.fromDate).toBe(getDate(false)); - }); - }); - - describe('By default, on init', () => { - it('should set all default values correctly', () => { - fixture.detectChanges(); - expect(comp.toDate).toBe(getDate()); - expect(comp.fromDate).toBe(getDate(false)); - expect(comp.itemsPerPage).toBe(ITEMS_PER_PAGE); - expect(comp.page).toBe(10); - expect(comp.reverse).toBeFalsy(); - }); - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - const audit = new Audit({ remoteAddress: '127.0.0.1', sessionId: '123' }, 'user', '20140101', 'AUTHENTICATION_SUCCESS'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [audit], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.audits[0]).toEqual(jasmine.objectContaining(audit)); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts b/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts deleted file mode 100644 index f9867f0551d0..000000000000 --- a/src/test/javascript/spec/app/admin/audits/audits.service.spec.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { AuditsService } from 'app/admin/audits/audits.service'; -import { Audit } from 'app/admin/audits/audit.model'; -import { SERVER_API_URL } from 'app/app.constants'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; - -describe('Service Tests', () => { - describe('Audits Service', () => { - let service: AuditsService; - let httpMock; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - - service = TestBed.inject(AuditsService); - httpMock = TestBed.inject(HttpTestingController); - }); - - afterEach(() => { - httpMock.verify(); - }); - - describe('Service methods', () => { - it('should call correct URL', () => { - service.query({}).subscribe(() => {}); - - const req = httpMock.expectOne({ method: 'GET' }); - const resourceUrl = SERVER_API_URL + 'management/audits'; - expect(req.request.url).toEqual(resourceUrl); - }); - - it('should return Audits', () => { - const audit = new Audit({ remoteAddress: '127.0.0.1', sessionId: '123' }, 'user', '20140101', 'AUTHENTICATION_SUCCESS'); - - service.query({}).subscribe((received) => { - expect(received.body[0]).toEqual(audit); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush([audit]); - }); - - it('should propagate not found response', () => { - service.query({}).subscribe(null, (_error: any) => { - expect(_error.status).toEqual(404); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush('Invalid request parameters', { - status: 404, - statusText: 'Bad Request', - }); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts b/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts deleted file mode 100644 index b479bc246952..000000000000 --- a/src/test/javascript/spec/app/admin/configuration/configuration.component.spec.ts +++ /dev/null @@ -1,68 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { JhiConfigurationComponent } from 'app/admin/configuration/configuration.component'; -import { JhiConfigurationService } from 'app/admin/configuration/configuration.service'; - -describe('Component Tests', () => { - describe('JhiConfigurationComponent', () => { - let comp: JhiConfigurationComponent; - let fixture: ComponentFixture; - let service: JhiConfigurationService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [JhiConfigurationComponent], - providers: [JhiConfigurationService], - }) - .overrideTemplate(JhiConfigurationComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(JhiConfigurationComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(JhiConfigurationService); - }); - - describe('OnInit', () => { - it('should set all default values correctly', () => { - expect(comp.configKeys).toEqual([]); - expect(comp.filter).toBe(''); - expect(comp.orderProp).toBe('prefix'); - expect(comp.reverse).toBe(false); - }); - it('Should call load all on init', () => { - // GIVEN - const body = [{ config: 'test', properties: 'test' }, { config: 'test2' }]; - const envConfig = { envConfig: 'test' }; - spyOn(service, 'get').and.returnValue(of(body)); - spyOn(service, 'getEnv').and.returnValue(of(envConfig)); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.get).toHaveBeenCalled(); - expect(service.getEnv).toHaveBeenCalled(); - expect(comp.configKeys).toEqual([['0', '1', '2', '3']]); - expect(comp.allConfiguration).toEqual(envConfig); - }); - }); - describe('keys method', () => { - it('should return the keys of an Object', () => { - // GIVEN - const data = { - key1: 'test', - key2: 'test2', - }; - - // THEN - expect(comp.keys(data)).toEqual(['key1', 'key2']); - expect(comp.keys(undefined)).toEqual([]); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts b/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts deleted file mode 100644 index 30bb8d0cb64b..000000000000 --- a/src/test/javascript/spec/app/admin/configuration/configuration.service.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { JhiConfigurationService } from 'app/admin/configuration/configuration.service'; -import { SERVER_API_URL } from 'app/app.constants'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { HttpResponse } from '@angular/common/http'; - -describe('Service Tests', () => { - describe('Logs Service', () => { - let service: JhiConfigurationService; - let httpMock; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - - service = TestBed.inject(JhiConfigurationService); - httpMock = TestBed.inject(HttpTestingController); - }); - - afterEach(() => { - httpMock.verify(); - }); - - describe('Service methods', () => { - it('should call correct URL', () => { - service.get().subscribe(() => {}); - - const req = httpMock.expectOne({ method: 'GET' }); - const resourceUrl = SERVER_API_URL + 'management/configprops'; - expect(req.request.url).toEqual(resourceUrl); - }); - - it('should get the config', () => { - const angularConfig = { - contexts: { - angular: { - beans: ['test2'], - }, - }, - }; - service.get().subscribe((received) => { - expect(received.body[0]).toEqual(angularConfig); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(angularConfig); - }); - - it('should get the env', () => { - const propertySources = new HttpResponse({ - body: [ - { name: 'test1', properties: 'test1' }, - { name: 'test2', properties: 'test2' }, - ], - }); - service.get().subscribe((received) => { - expect(received.body[0]).toEqual(propertySources); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(propertySources); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/health/health.component.spec.ts b/src/test/javascript/spec/app/admin/health/health.component.spec.ts deleted file mode 100644 index 45f32f3ddfc4..000000000000 --- a/src/test/javascript/spec/app/admin/health/health.component.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { HttpErrorResponse } from '@angular/common/http'; -import { of, throwError } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { HealthComponent } from 'app/admin/health/health.component'; -import { Health, HealthService } from 'app/admin/health/health.service'; - -describe('Component Tests', () => { - describe('HealthComponent', () => { - let comp: HealthComponent; - let fixture: ComponentFixture; - let service: HealthService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [HealthComponent], - }) - .overrideTemplate(HealthComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(HealthComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(HealthService); - }); - - describe('getBadgeClass', () => { - it('should get badge class', () => { - const upBadgeClass = comp.getBadgeClass('UP'); - const downBadgeClass = comp.getBadgeClass('DOWN'); - expect(upBadgeClass).toEqual('badge-success'); - expect(downBadgeClass).toEqual('badge-danger'); - }); - }); - - describe('refresh', () => { - it('should call refresh on init', () => { - // GIVEN - const health: Health = { status: 'UP', components: { mail: { status: 'UP', details: 'mailDetails' } } }; - spyOn(service, 'checkHealth').and.returnValue(of(health)); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.checkHealth).toHaveBeenCalled(); - expect(comp.health).toEqual(health); - }); - - it('should handle a 503 on refreshing health data', () => { - // GIVEN - const health: Health = { status: 'DOWN', components: { mail: { status: 'DOWN', details: 'mailDetails' } } }; - spyOn(service, 'checkHealth').and.returnValue(throwError(new HttpErrorResponse({ status: 503, error: health }))); - - // WHEN - comp.refresh(); - - // THEN - expect(service.checkHealth).toHaveBeenCalled(); - expect(comp.health).toEqual(health); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts b/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts deleted file mode 100644 index 68f11e5dd5bf..000000000000 --- a/src/test/javascript/spec/app/admin/logs/logs.component.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { LogsComponent } from 'app/admin/logs/logs.component'; -import { LogsService } from 'app/admin/logs/logs.service'; -import { Log } from 'app/admin'; - -describe('Component Tests', () => { - describe('LogsComponent', () => { - let comp: LogsComponent; - let fixture: ComponentFixture; - let service: LogsService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [LogsComponent], - providers: [LogsService], - }) - .overrideTemplate(LogsComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(LogsComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(LogsService); - }); - - describe('OnInit', () => { - it('should set all default values correctly', () => { - expect(comp.filter).toBe(''); - expect(comp.orderProp).toBe('name'); - expect(comp.reverse).toBe(false); - }); - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - const log = new Log('main', 'WARN'); - spyOn(service, 'findAll').and.returnValue( - of( - new HttpResponse({ - body: [log], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.findAll).toHaveBeenCalled(); - expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log)); - }); - }); - describe('change log level', () => { - it('should change log level correctly', () => { - // GIVEN - const log = new Log('main', 'ERROR'); - spyOn(service, 'changeLevel').and.returnValue(of(new HttpResponse())); - spyOn(service, 'findAll').and.returnValue(of(new HttpResponse({ body: [log] }))); - - // WHEN - comp.changeLevel('main', 'ERROR'); - - // THEN - expect(service.changeLevel).toHaveBeenCalled(); - expect(service.findAll).toHaveBeenCalled(); - expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log)); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts b/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts deleted file mode 100644 index 90fddfc143e6..000000000000 --- a/src/test/javascript/spec/app/admin/logs/logs.service.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { LogsService } from 'app/admin/logs/logs.service'; -import { Log } from 'app/admin/logs/log.model'; -import { SERVER_API_URL } from 'app/app.constants'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; - -describe('Service Tests', () => { - describe('Logs Service', () => { - let service: LogsService; - let httpMock; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - - service = TestBed.inject(LogsService); - httpMock = TestBed.inject(HttpTestingController); - }); - - afterEach(() => { - httpMock.verify(); - }); - - describe('Service methods', () => { - it('should call correct URL', () => { - service.findAll().subscribe(() => {}); - - const req = httpMock.expectOne({ method: 'GET' }); - const resourceUrl = SERVER_API_URL + 'management/logs'; - expect(req.request.url).toEqual(resourceUrl); - }); - - it('should return Logs', () => { - const log = new Log('main', 'ERROR'); - - service.findAll().subscribe((received) => { - expect(received.body[0]).toEqual(log); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush([log]); - }); - - it('should change log level', () => { - const log = new Log('main', 'ERROR'); - - service.changeLevel(log).subscribe((received) => { - expect(received.body[0]).toEqual(log); - }); - - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush([log]); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/metrics/metrics-modal.component.spec.ts b/src/test/javascript/spec/app/admin/metrics/metrics-modal.component.spec.ts deleted file mode 100644 index 9495c6ad7444..000000000000 --- a/src/test/javascript/spec/app/admin/metrics/metrics-modal.component.spec.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; - -import { ArtemisTestModule } from '../../../test.module'; -import { JhiMetricsMonitoringModalComponent } from 'app/admin/metrics/metrics-modal.component'; -import { JhiMetricsService } from 'app/admin/metrics/metrics.service'; - -describe('Component Tests', () => { - describe('JhiMetricsMonitoringModalComponent', () => { - let comp: JhiMetricsMonitoringModalComponent; - let fixture: ComponentFixture; - let service: JhiMetricsService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [JhiMetricsMonitoringModalComponent], - }) - .overrideTemplate(JhiMetricsMonitoringModalComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(JhiMetricsMonitoringModalComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(JhiMetricsService); - }); - - describe('ngOnInit', () => { - it('should count the numbers of each thread type', () => { - comp.threadDump = [ - { name: 'test1', threadState: 'RUNNABLE' }, - { name: 'test2', threadState: 'WAITING' }, - { name: 'test3', threadState: 'TIMED_WAITING' }, - { name: 'test4', threadState: 'BLOCKED' }, - { name: 'test5', threadState: 'BLOCKED' }, - { name: 'test5', threadState: 'NONE' }, - ]; - fixture.detectChanges(); - - expect(comp.threadDumpRunnable).toBe(1); - expect(comp.threadDumpWaiting).toBe(1); - expect(comp.threadDumpTimedWaiting).toBe(1); - expect(comp.threadDumpBlocked).toBe(2); - expect(comp.threadDumpAll).toBe(5); - }); - - it('should return badge-info for WAITING', () => { - expect(comp.getBadgeClass('WAITING')).toBe('badge-info'); - }); - - it('should return badge-warning for TIMED_WAITING', () => { - expect(comp.getBadgeClass('TIMED_WAITING')).toBe('badge-warning'); - }); - - it('should return badge-danger for BLOCKED', () => { - expect(comp.getBadgeClass('BLOCKED')).toBe('badge-danger'); - }); - - it('should return undefined for anything else', () => { - expect(comp.getBadgeClass('')).toBe(undefined); - }); - }); - - describe('getBadgeClass', () => { - it('should return badge-success for RUNNABLE', () => { - expect(comp.getBadgeClass('RUNNABLE')).toBe('badge-success'); - }); - - it('should return badge-info for WAITING', () => { - expect(comp.getBadgeClass('WAITING')).toBe('badge-info'); - }); - - it('should return badge-warning for TIMED_WAITING', () => { - expect(comp.getBadgeClass('TIMED_WAITING')).toBe('badge-warning'); - }); - - it('should return badge-danger for BLOCKED', () => { - expect(comp.getBadgeClass('BLOCKED')).toBe('badge-danger'); - }); - - it('should return undefined for anything else', () => { - expect(comp.getBadgeClass('')).toBe(undefined); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts b/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts deleted file mode 100644 index 6b44e69e26d2..000000000000 --- a/src/test/javascript/spec/app/admin/metrics/metrics.component.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { JhiMetricsMonitoringComponent } from 'app/admin/metrics/metrics.component'; -import { JhiMetricsService } from 'app/admin/metrics/metrics.service'; - -describe('Component Tests', () => { - describe('JhiMetricsMonitoringComponent', () => { - let comp: JhiMetricsMonitoringComponent; - let fixture: ComponentFixture; - let service: JhiMetricsService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [JhiMetricsMonitoringComponent], - }) - .overrideTemplate(JhiMetricsMonitoringComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(JhiMetricsMonitoringComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(JhiMetricsService); - }); - - describe('refresh', () => { - it('should call refresh on init', () => { - // GIVEN - const response = { - timers: { - service: 'test', - unrelatedKey: 'test', - }, - gauges: { - 'jcache.statistics': { - value: 2, - }, - unrelatedKey: 'test', - }, - }; - spyOn(service, 'getMetrics').and.returnValue(of(response)); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.getMetrics).toHaveBeenCalled(); - expect(comp.servicesStats).toEqual({ service: 'test' }); - expect(comp.cachesStats).toEqual({ jcache: { name: 17, value: 2 } }); - }); - }); - - describe('isNan', () => { - it('should return if a variable is NaN', () => { - expect(comp.filterNaN(1)).toBe(1); - expect(comp.filterNaN('test')).toBe(0); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts b/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts deleted file mode 100644 index af33f34c0696..000000000000 --- a/src/test/javascript/spec/app/admin/metrics/metrics.service.spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import { TestBed } from '@angular/core/testing'; - -import { JhiMetricsService } from 'app/admin/metrics/metrics.service'; -import { SERVER_API_URL } from 'app/app.constants'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; - -describe('Service Tests', () => { - describe('Logs Service', () => { - let service: JhiMetricsService; - let httpMock; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - - service = TestBed.inject(JhiMetricsService); - httpMock = TestBed.inject(HttpTestingController); - }); - - afterEach(() => { - httpMock.verify(); - }); - - describe('Service methods', () => { - it('should call correct URL', () => { - service.getMetrics().subscribe(() => {}); - - const req = httpMock.expectOne({ method: 'GET' }); - const resourceUrl = SERVER_API_URL + 'management/metrics'; - expect(req.request.url).toEqual(resourceUrl); - }); - - it('should return Metrics', () => { - const metrics = []; - - service.getMetrics().subscribe((received) => { - expect(received.body[0]).toEqual(metrics); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush([metrics]); - }); - - it('should return Thread Dump', () => { - const dump = [{ name: 'test1', threadState: 'RUNNABLE' }]; - - service.threadDump().subscribe((received) => { - expect(received.body[0]).toEqual(dump); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush([dump]); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts deleted file mode 100644 index 61aa9e27b53a..000000000000 --- a/src/test/javascript/spec/app/admin/user-management/user-management-delete-dialog.component.spec.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { UserManagementDeleteDialogComponent } from 'app/admin/user-management/user-management-delete-dialog.component'; -import { UserService } from 'app/core/user/user.service'; - -describe('Component Tests', () => { - describe('User Management Delete Component', () => { - let comp: UserManagementDeleteDialogComponent; - let fixture: ComponentFixture; - let service: UserService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [UserManagementDeleteDialogComponent], - }) - .overrideTemplate(UserManagementDeleteDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(UserManagementDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(UserService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete('user'); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith('user'); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts b/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts deleted file mode 100644 index fe56aa0c724c..000000000000 --- a/src/test/javascript/spec/app/admin/user-management/user-management-detail.component.spec.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { UserManagementDetailComponent } from 'app/admin/user-management/user-management-detail.component'; -import { User } from 'app/core/user/user.model'; - -describe('Component Tests', () => { - describe('User Management Detail Component', () => { - let comp: UserManagementDetailComponent; - let fixture: ComponentFixture; - const route = ({ - data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', ['ROLE_USER'], 'admin', null, null, null) }), - } as any) as ActivatedRoute; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [UserManagementDetailComponent], - providers: [ - { - provide: ActivatedRoute, - useValue: route, - }, - ], - }) - .overrideTemplate(UserManagementDetailComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(UserManagementDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.user).toEqual( - jasmine.objectContaining({ - id: 1, - login: 'user', - firstName: 'first', - lastName: 'last', - email: 'first@last.com', - activated: true, - langKey: 'en', - authorities: ['ROLE_USER'], - createdBy: 'admin', - createdDate: null, - lastModifiedBy: null, - lastModifiedDate: null, - password: null, - }), - ); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/user-management/user-management-dialog.component.spec.ts b/src/test/javascript/spec/app/admin/user-management/user-management-dialog.component.spec.ts deleted file mode 100644 index bd49d4264eb3..000000000000 --- a/src/test/javascript/spec/app/admin/user-management/user-management-dialog.component.spec.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { UserMgmtDialogComponent } from '../../../../../../main/webapp/app/admin/user-management/user-management-dialog.component'; -import { JhiLanguageHelper, User, UserService } from '../../../../../../main/webapp/app/shared'; - -describe('Component Tests', () => { - describe('User Management Dialog Component', () => { - let comp: UserMgmtDialogComponent; - let fixture: ComponentFixture; - let service: UserService; - let mockEventManager: any; - let mockActiveModal: any; - let mockLanguageHelper: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [UserMgmtDialogComponent], - providers: [UserService], - }) - .overrideTemplate(UserMgmtDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(UserMgmtDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(UserService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - mockLanguageHelper = fixture.debugElement.injector.get(JhiLanguageHelper); - }); - - describe('OnInit', () => { - it('Should load authorities and language on init', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'authorities').and.returnValue(Observable.of(['USER'])); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.authorities).toHaveBeenCalled(); - expect(comp.authorities).toEqual(['USER']); - expect(mockLanguageHelper.getAllSpy).toHaveBeenCalled(); - }), - )); - }); - - describe('save', () => { - it('Should call update service on save for existing user', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new User(123); - spyOn(service, 'update').and.returnValue( - Observable.of( - new HttpResponse({ - body: entity, - }), - ), - ); - comp.user = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'userListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new user', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new User(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.user = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'userListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts b/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts deleted file mode 100644 index 22b320dd9dcc..000000000000 --- a/src/test/javascript/spec/app/admin/user-management/user-management-update.component.spec.ts +++ /dev/null @@ -1,104 +0,0 @@ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { UserManagementUpdateComponent } from 'app/admin/user-management/user-management-update.component'; -import { User } from 'app/core/user/user.model'; -import { JhiLanguageHelper } from 'app/core/language/language.helper'; -import { UserService } from 'app/core/user/user.service'; - -describe('Component Tests', () => { - describe('User Management Update Component', () => { - let comp: UserManagementUpdateComponent; - let fixture: ComponentFixture; - let service: UserService; - let mockLanguageHelper: any; - const route = ({ - data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', ['ROLE_USER'], 'admin', null, null, null) }), - } as any) as ActivatedRoute; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [UserManagementUpdateComponent], - providers: [ - { - provide: ActivatedRoute, - useValue: route, - }, - ], - }) - .overrideTemplate(UserManagementUpdateComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(UserManagementUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(UserService); - mockLanguageHelper = fixture.debugElement.injector.get(JhiLanguageHelper); - }); - - describe('OnInit', () => { - it('Should load authorities and language on init', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'authorities').and.returnValue(of(['USER'])); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.authorities).toHaveBeenCalled(); - expect(comp.authorities).toEqual(['USER']); - expect(mockLanguageHelper.getAllSpy).toHaveBeenCalled(); - }), - )); - }); - - describe('save', () => { - it('Should call update service on save for existing user', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new User(123); - spyOn(service, 'update').and.returnValue( - of( - new HttpResponse({ - body: entity, - }), - ), - ); - comp.user = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - }), - )); - - it('Should call create service on save for new user', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new User(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.user = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts b/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts deleted file mode 100644 index 40dbc5bdfa41..000000000000 --- a/src/test/javascript/spec/app/admin/user-management/user-management.component.spec.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { UserManagementComponent } from 'app/admin/user-management/user-management.component'; -import { User } from 'app/core/user/user.model'; -import { UserService } from 'app/core/user/user.service'; - -describe('Component Tests', () => { - describe('User Management Component', () => { - let comp: UserManagementComponent; - let fixture: ComponentFixture; - let service: UserService; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [UserManagementComponent], - }) - .overrideTemplate(UserManagementComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(UserManagementComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(UserService); - }); - - describe('OnInit', () => { - it('Should call load all on init', inject( - [], - fakeAsync(() => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new User(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - tick(); // simulate async - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.users[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }), - )); - }); - - describe('setActive', () => { - it('Should update user and call load all', inject( - [], - fakeAsync(() => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - const user = new User(123); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [user], - headers, - }), - ), - ); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ status: 200 }))); - - // WHEN - comp.setActive(user, true); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(user); - expect(service.query).toHaveBeenCalled(); - expect(comp.users[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/core/user/user.service.spec.ts b/src/test/javascript/spec/app/core/user/user.service.spec.ts deleted file mode 100644 index a69ddc4f18de..000000000000 --- a/src/test/javascript/spec/app/core/user/user.service.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { TestBed } from '@angular/core/testing'; -import { JhiDateUtils } from 'ng-jhipster'; - -import { User } from 'app/core/user/user.model'; -import { UserService } from 'app/core/user/user.service'; -import { SERVER_API_URL } from 'app/app.constants'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; - -describe('Service Tests', () => { - describe('User Service', () => { - let service: UserService; - let httpMock; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [JhiDateUtils], - }); - - service = TestBed.inject(UserService); - httpMock = TestBed.inject(HttpTestingController); - }); - - afterEach(() => { - httpMock.verify(); - }); - - describe('Service methods', () => { - it('should call correct URL', () => { - service.find('user').subscribe(() => {}); - - const req = httpMock.expectOne({ method: 'GET' }); - const resourceUrl = SERVER_API_URL + 'api/users'; - expect(req.request.url).toEqual(`${resourceUrl}/user`); - }); - it('should return User', () => { - service.find('user').subscribe((received) => { - expect(received.body.login).toEqual('user'); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(new User(1, 'user')); - }); - - it('should return Authorities', () => { - service.authorities().subscribe((_authorities) => { - expect(_authorities).toEqual(['ROLE_USER', 'ROLE_ADMIN']); - }); - const req = httpMock.expectOne({ method: 'GET' }); - - req.flush(['ROLE_USER', 'ROLE_ADMIN']); - }); - - it('should propagate not found response', () => { - service.find('user').subscribe(null, (_error: any) => { - expect(_error.status).toEqual(404); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush('Invalid request parameters', { - status: 404, - statusText: 'Bad Request', - }); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/course/course-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/course/course-delete-dialog.component.spec.ts deleted file mode 100644 index 6bc78bd911d6..000000000000 --- a/src/test/javascript/spec/app/entities/course/course-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { CourseDeleteDialogComponent } from 'app/entities/manage/course-delete-dialog.component'; -import { CourseService } from 'app/course/manage/course.service'; - -describe('Component Tests', () => { - describe('Course Management Delete Component', () => { - let comp: CourseDeleteDialogComponent; - let fixture: ComponentFixture; - let service: CourseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [CourseDeleteDialogComponent], - }) - .overrideTemplate(CourseDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(CourseDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(CourseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/course/course-detail.component.spec.ts b/src/test/javascript/spec/app/entities/course/course-detail.component.spec.ts deleted file mode 100644 index fbc54243c480..000000000000 --- a/src/test/javascript/spec/app/entities/course/course-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { CourseDetailComponent } from 'app/entities/manage/course-detail.component'; -import { Course } from 'app/shared/model/course.model'; - -describe('Component Tests', () => { - describe('Course Management Detail Component', () => { - let comp: CourseDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ course: new Course(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [CourseDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(CourseDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(CourseDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.course).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/course/course-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/course/course-dialog.component.spec.ts deleted file mode 100644 index b3feb9d9c304..000000000000 --- a/src/test/javascript/spec/app/entities/course/course-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { CourseDialogComponent } from '../../../../../../main/webapp/app/entities/manage/course-dialog.component'; -import { CourseService } from '../../../../../../main/webapp/app/entities/manage/course.service'; -import { Course } from 'app/entities/course.model'; - -describe('Component Tests', () => { - describe('Course Management Dialog Component', () => { - let comp: CourseDialogComponent; - let fixture: ComponentFixture; - let service: CourseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [CourseDialogComponent], - providers: [CourseService], - }) - .overrideTemplate(CourseDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(CourseDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(CourseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new Course(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.course = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'courseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new Course(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.course = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'courseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/course/course-update.component.spec.ts b/src/test/javascript/spec/app/entities/course/course-update.component.spec.ts deleted file mode 100644 index fd0f0d4850bc..000000000000 --- a/src/test/javascript/spec/app/entities/course/course-update.component.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { CourseUpdateComponent } from 'app/entities/manage/course-update.component'; -import { CourseService } from 'app/course/manage/course.service'; -import { Course } from 'app/entities/course.model'; - -describe('Component Tests', () => { - describe('Course Management Update Component', () => { - let comp: CourseUpdateComponent; - let fixture: ComponentFixture; - let service: CourseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [CourseUpdateComponent], - }) - .overrideTemplate(CourseUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(CourseUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(CourseService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new Course(); - entity.id = 123; - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.course = entity; - comp.courseForm = { value: entity }; // mocking reactive form - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new Course(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.course = entity; - comp.courseForm = { value: entity }; // mocking reactive form - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/course/course.component.spec.ts b/src/test/javascript/spec/app/entities/course/course.component.spec.ts deleted file mode 100644 index 55ddbc38f38c..000000000000 --- a/src/test/javascript/spec/app/entities/course/course.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { CourseComponent } from 'app/entities/manage/course.component'; -import { CourseService } from 'app/course/manage/course.service'; -import { Course } from 'app/shared/model/course.model'; - -describe('Component Tests', () => { - describe('Course Management Component', () => { - let comp: CourseComponent; - let fixture: ComponentFixture; - let service: CourseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [CourseComponent], - providers: [], - }) - .overrideTemplate(CourseComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(CourseComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(CourseService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new Course(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.courses[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/course/course.service.spec.ts b/src/test/javascript/spec/app/entities/course/course.service.spec.ts deleted file mode 100644 index a69afafe2191..000000000000 --- a/src/test/javascript/spec/app/entities/course/course.service.spec.ts +++ /dev/null @@ -1,144 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import * as moment from 'moment'; -import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; -import { CourseService } from 'app/course/manage/course.service'; -import { Course, ICourse } from 'app/shared/model/course.model'; - -describe('Service Tests', () => { - describe('Course Service', () => { - let injector: TestBed; - let service: CourseService; - let httpMock: HttpTestingController; - let elemDefault: ICourse; - let currentDate: moment.Moment; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(CourseService); - httpMock = injector.get(HttpTestingController); - currentDate = moment(); - - elemDefault = new Course(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', currentDate, currentDate, false); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign( - { - startDate: currentDate.format(DATE_TIME_FORMAT), - endDate: currentDate.format(DATE_TIME_FORMAT), - }, - elemDefault, - ); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a Course', async () => { - const returnedFromService = Object.assign( - { - id: 0, - startDate: currentDate.format(DATE_TIME_FORMAT), - endDate: currentDate.format(DATE_TIME_FORMAT), - }, - elemDefault, - ); - const expected = Object.assign( - { - startDate: currentDate, - endDate: currentDate, - }, - returnedFromService, - ); - service - .create(new Course(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a Course', async () => { - const returnedFromService = Object.assign( - { - title: 'BBBBBB', - studentGroupName: 'BBBBBB', - teachingAssistantGroupName: 'BBBBBB', - instructorGroupName: 'BBBBBB', - startDate: currentDate.format(DATE_TIME_FORMAT), - endDate: currentDate.format(DATE_TIME_FORMAT), - onlineCourse: true, - }, - elemDefault, - ); - - const expected = Object.assign( - { - startDate: currentDate, - endDate: currentDate, - }, - returnedFromService, - ); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of Course', async () => { - const returnedFromService = Object.assign( - { - title: 'BBBBBB', - studentGroupName: 'BBBBBB', - teachingAssistantGroupName: 'BBBBBB', - instructorGroupName: 'BBBBBB', - startDate: currentDate.format(DATE_TIME_FORMAT), - endDate: currentDate.format(DATE_TIME_FORMAT), - onlineCourse: true, - }, - elemDefault, - ); - const expected = Object.assign( - { - startDate: currentDate, - endDate: currentDate, - }, - returnedFromService, - ); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a Course', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-detail.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-detail.component.spec.ts deleted file mode 100644 index 99cd0a3af9fe..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadExerciseDetailComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-detail.component'; -import { FileUploadExercise } from 'app/shared/model/file-upload-exercise.model'; - -describe('Component Tests', () => { - describe('FileUploadExercise Management Detail Component', () => { - let comp: FileUploadExerciseDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ fileUploadExercise: new FileUploadExercise(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadExerciseDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(FileUploadExerciseDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(FileUploadExerciseDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.fileUploadExercise).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-dialog.component.spec.ts deleted file mode 100644 index cd20d11e44d3..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { FileUploadExerciseDialogComponent } from '../../../../../../main/webapp/app/exercises/file-upload/manage/file-upload-exercise/file-upload-exercise-dialog.component'; -import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; -import { FileUploadExercise } from 'app/entities/file-upload-exercise.model'; - -describe('Component Tests', () => { - describe('FileUploadExercise Management Dialog Component', () => { - let comp: FileUploadExerciseDialogComponent; - let fixture: ComponentFixture; - let service: FileUploadExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [FileUploadExerciseDialogComponent], - providers: [FileUploadExerciseService], - }) - .overrideTemplate(FileUploadExerciseDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(FileUploadExerciseDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new FileUploadExercise(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.fileUploadExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'fileUploadExerciseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new FileUploadExercise(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.fileUploadExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'fileUploadExerciseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-update.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-update.component.spec.ts deleted file mode 100644 index e017d6534e72..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadExerciseUpdateComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-update.component'; -import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; -import { FileUploadExercise } from 'app/shared/model/file-upload-exercise.model'; - -describe('Component Tests', () => { - describe('FileUploadExercise Management Update Component', () => { - let comp: FileUploadExerciseUpdateComponent; - let fixture: ComponentFixture; - let service: FileUploadExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadExerciseUpdateComponent], - }) - .overrideTemplate(FileUploadExerciseUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(FileUploadExerciseUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadExerciseService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new FileUploadExercise(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.fileUploadExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new FileUploadExercise(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.fileUploadExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise.component.spec.ts deleted file mode 100644 index ebb275735301..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadExerciseComponent } from 'app/exercises/file-upload/manage/file-upload-exercise.component'; -import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; -import { FileUploadExercise } from 'app/shared/model/file-upload-exercise.model'; - -describe('Component Tests', () => { - describe('FileUploadExercise Management Component', () => { - let comp: FileUploadExerciseComponent; - let fixture: ComponentFixture; - let service: FileUploadExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadExerciseComponent], - providers: [], - }) - .overrideTemplate(FileUploadExerciseComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(FileUploadExerciseComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadExerciseService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new FileUploadExercise(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.fileUploadExercises[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise.service.spec.ts b/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise.service.spec.ts deleted file mode 100644 index 7c7d8ed2ed8f..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-exercise/file-upload-exercise.service.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; -import { FileUploadExercise, IFileUploadExercise } from 'app/shared/model/file-upload-exercise.model'; - -describe('Service Tests', () => { - describe('FileUploadExercise Service', () => { - let injector: TestBed; - let service: FileUploadExerciseService; - let httpMock: HttpTestingController; - let elemDefault: IFileUploadExercise; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(FileUploadExerciseService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new FileUploadExercise(0, 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a FileUploadExercise', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new FileUploadExercise(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a FileUploadExercise', async () => { - const returnedFromService = Object.assign( - { - filePattern: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of FileUploadExercise', async () => { - const returnedFromService = Object.assign( - { - filePattern: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a FileUploadExercise', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-delete-dialog.component.spec.ts deleted file mode 100644 index a96d79a80d0a..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadSubmissionDeleteDialogComponent } from 'app/exercises/file-upload-submission/file-upload-submission-delete-dialog.component'; -import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service'; - -describe('Component Tests', () => { - describe('FileUploadSubmission Management Delete Component', () => { - let comp: FileUploadSubmissionDeleteDialogComponent; - let fixture: ComponentFixture; - let service: FileUploadSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadSubmissionDeleteDialogComponent], - }) - .overrideTemplate(FileUploadSubmissionDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(FileUploadSubmissionDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-detail.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-detail.component.spec.ts deleted file mode 100644 index 42932d000fc5..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadSubmissionDetailComponent } from 'app/exercises/file-upload-submission/file-upload-submission-detail.component'; -import { FileUploadSubmission } from 'app/shared/model/file-upload-submission.model'; - -describe('Component Tests', () => { - describe('FileUploadSubmission Management Detail Component', () => { - let comp: FileUploadSubmissionDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ fileUploadSubmission: new FileUploadSubmission(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadSubmissionDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(FileUploadSubmissionDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(FileUploadSubmissionDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.fileUploadSubmission).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-dialog.component.spec.ts deleted file mode 100644 index 12ee8b7e28fe..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { FileUploadSubmissionDialogComponent } from '../../../../../../main/webapp/app/exercises/file-upload-submission/file-upload-submission-dialog.component'; -import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service'; -import { FileUploadSubmission } from 'app/entities/file-upload-submission.model'; - -describe('Component Tests', () => { - describe('FileUploadSubmission Management Dialog Component', () => { - let comp: FileUploadSubmissionDialogComponent; - let fixture: ComponentFixture; - let service: FileUploadSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [FileUploadSubmissionDialogComponent], - providers: [FileUploadSubmissionService], - }) - .overrideTemplate(FileUploadSubmissionDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(FileUploadSubmissionDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new FileUploadSubmission(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.fileUploadSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'fileUploadSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new FileUploadSubmission(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.fileUploadSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'fileUploadSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-update.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-update.component.spec.ts deleted file mode 100644 index 2edb54c85048..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadSubmissionUpdateComponent } from 'app/exercises/file-upload-submission/file-upload-submission-update.component'; -import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service'; -import { FileUploadSubmission } from 'app/shared/model/file-upload-submission.model'; - -describe('Component Tests', () => { - describe('FileUploadSubmission Management Update Component', () => { - let comp: FileUploadSubmissionUpdateComponent; - let fixture: ComponentFixture; - let service: FileUploadSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadSubmissionUpdateComponent], - }) - .overrideTemplate(FileUploadSubmissionUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(FileUploadSubmissionUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadSubmissionService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new FileUploadSubmission(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.fileUploadSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new FileUploadSubmission(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.fileUploadSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission.component.spec.ts b/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission.component.spec.ts deleted file mode 100644 index fddebd5ba11c..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { FileUploadSubmissionComponent } from 'app/exercises/file-upload-submission/file-upload-submission.component'; -import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service'; -import { FileUploadSubmission } from 'app/shared/model/file-upload-submission.model'; - -describe('Component Tests', () => { - describe('FileUploadSubmission Management Component', () => { - let comp: FileUploadSubmissionComponent; - let fixture: ComponentFixture; - let service: FileUploadSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [FileUploadSubmissionComponent], - providers: [], - }) - .overrideTemplate(FileUploadSubmissionComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(FileUploadSubmissionComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(FileUploadSubmissionService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new FileUploadSubmission(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.fileUploadSubmissions[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission.service.spec.ts b/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission.service.spec.ts deleted file mode 100644 index 48ab8418bdcd..000000000000 --- a/src/test/javascript/spec/app/entities/file-upload-submission/file-upload-submission.service.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service'; -import { FileUploadSubmission, IFileUploadSubmission } from 'app/shared/model/file-upload-submission.model'; - -describe('Service Tests', () => { - describe('FileUploadSubmission Service', () => { - let injector: TestBed; - let service: FileUploadSubmissionService; - let httpMock: HttpTestingController; - let elemDefault: IFileUploadSubmission; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(FileUploadSubmissionService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new FileUploadSubmission(0, 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a FileUploadSubmission', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new FileUploadSubmission(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a FileUploadSubmission', async () => { - const returnedFromService = Object.assign( - { - filePath: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of FileUploadSubmission', async () => { - const returnedFromService = Object.assign( - { - filePath: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a FileUploadSubmission', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-delete-dialog.component.spec.ts deleted file mode 100644 index c350676ee7d6..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingExerciseDeleteDialogComponent } from 'app/exercises/modeling/manage/modeling-exercise/modeling-exercise-delete-dialog.component'; -import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; - -describe('Component Tests', () => { - describe('ModelingExercise Management Delete Component', () => { - let comp: ModelingExerciseDeleteDialogComponent; - let fixture: ComponentFixture; - let service: ModelingExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingExerciseDeleteDialogComponent], - }) - .overrideTemplate(ModelingExerciseDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ModelingExerciseDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-detail.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-detail.component.spec.ts deleted file mode 100644 index db3a25ca63f2..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingExerciseDetailComponent } from 'app/exercises/modeling/manage/modeling-exercise-detail.component'; -import { ModelingExercise } from 'app/shared/model/modeling-exercise.model'; - -describe('Component Tests', () => { - describe('ModelingExercise Management Detail Component', () => { - let comp: ModelingExerciseDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ modelingExercise: new ModelingExercise(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingExerciseDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(ModelingExerciseDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ModelingExerciseDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.modelingExercise).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-dialog.component.spec.ts deleted file mode 100644 index b63e2c15c632..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-dialog.component.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingExerciseDialogComponent } from '../../../../../../main/webapp/app/exercises/modeling/manage/modeling-exercise/modeling-exercise-dialog.component'; -import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; -import { ModelingExercise } from 'app/entities/modeling-exercise.model'; -import { UMLDiagramType } from '@ls1intum/apollon'; - -describe('Component Tests', () => { - describe('ModelingExercise Management Dialog Component', () => { - let comp: ModelingExerciseDialogComponent; - let fixture: ComponentFixture; - let service: ModelingExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingExerciseDialogComponent], - providers: [ModelingExerciseService], - }) - .overrideTemplate(ModelingExerciseDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(ModelingExerciseDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new ModelingExercise(UMLDiagramType.ClassDiagram); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.modelingExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'modelingExerciseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new ModelingExercise(UMLDiagramType.ClassDiagram); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.modelingExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'modelingExerciseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-update.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-update.component.spec.ts deleted file mode 100644 index af9603e9ea54..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingExerciseUpdateComponent } from 'app/exercises/modeling/manage/modeling-exercise-update.component'; -import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; -import { ModelingExercise } from 'app/shared/model/modeling-exercise.model'; - -describe('Component Tests', () => { - describe('ModelingExercise Management Update Component', () => { - let comp: ModelingExerciseUpdateComponent; - let fixture: ComponentFixture; - let service: ModelingExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingExerciseUpdateComponent], - }) - .overrideTemplate(ModelingExerciseUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ModelingExerciseUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingExerciseService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new ModelingExercise(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.modelingExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new ModelingExercise(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.modelingExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise.component.spec.ts deleted file mode 100644 index 868352cd2a6b..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingExerciseComponent } from 'app/exercises/modeling/manage/modeling-exercise.component'; -import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; -import { ModelingExercise } from 'app/shared/model/modeling-exercise.model'; - -describe('Component Tests', () => { - describe('ModelingExercise Management Component', () => { - let comp: ModelingExerciseComponent; - let fixture: ComponentFixture; - let service: ModelingExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingExerciseComponent], - providers: [], - }) - .overrideTemplate(ModelingExerciseComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ModelingExerciseComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingExerciseService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new ModelingExercise(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.modelingExercises[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise.service.spec.ts b/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise.service.spec.ts deleted file mode 100644 index d749f9d379aa..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-exercise/modeling-exercise.service.spec.ts +++ /dev/null @@ -1,106 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; -import { DiagramType, IModelingExercise, ModelingExercise } from 'app/shared/model/modeling-exercise.model'; - -describe('Service Tests', () => { - describe('ModelingExercise Service', () => { - let injector: TestBed; - let service: ModelingExerciseService; - let httpMock: HttpTestingController; - let elemDefault: IModelingExercise; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(ModelingExerciseService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new ModelingExercise(0, DiagramType.CLASS, 'AAAAAAA', 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a ModelingExercise', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new ModelingExercise(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a ModelingExercise', async () => { - const returnedFromService = Object.assign( - { - diagramType: 'BBBBBB', - sampleSolutionModel: 'BBBBBB', - sampleSolutionExplanation: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of ModelingExercise', async () => { - const returnedFromService = Object.assign( - { - diagramType: 'BBBBBB', - sampleSolutionModel: 'BBBBBB', - sampleSolutionExplanation: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a ModelingExercise', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-delete-dialog.component.spec.ts deleted file mode 100644 index 93325c7eb7a9..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingSubmissionDeleteDialogComponent } from 'app/exercises/modeling-submission/modeling-submission-delete-dialog.component'; -import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; - -describe('Component Tests', () => { - describe('ModelingSubmission Management Delete Component', () => { - let comp: ModelingSubmissionDeleteDialogComponent; - let fixture: ComponentFixture; - let service: ModelingSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingSubmissionDeleteDialogComponent], - }) - .overrideTemplate(ModelingSubmissionDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ModelingSubmissionDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-detail.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-detail.component.spec.ts deleted file mode 100644 index fdf981d844e3..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingSubmissionDetailComponent } from 'app/exercises/modeling-submission/modeling-submission-detail.component'; -import { ModelingSubmission } from 'app/shared/model/modeling-submission.model'; - -describe('Component Tests', () => { - describe('ModelingSubmission Management Detail Component', () => { - let comp: ModelingSubmissionDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ modelingSubmission: new ModelingSubmission(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingSubmissionDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(ModelingSubmissionDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ModelingSubmissionDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.modelingSubmission).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-dialog.component.spec.ts deleted file mode 100644 index 69abf45849e9..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingSubmissionDialogComponent } from '../../../../../../main/webapp/app/exercises/modeling-submission/modeling-submission-dialog.component'; -import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; -import { ModelingSubmission } from 'app/entities/modeling-submission.model'; - -describe('Component Tests', () => { - describe('ModelingSubmission Management Dialog Component', () => { - let comp: ModelingSubmissionDialogComponent; - let fixture: ComponentFixture; - let service: ModelingSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingSubmissionDialogComponent], - providers: [ModelingSubmissionService], - }) - .overrideTemplate(ModelingSubmissionDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(ModelingSubmissionDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new ModelingSubmission(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.modelingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'modelingSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new ModelingSubmission(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.modelingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'modelingSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-update.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-update.component.spec.ts deleted file mode 100644 index 4f5ff308343c..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingSubmissionUpdateComponent } from 'app/exercises/modeling-submission/modeling-submission-update.component'; -import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; -import { ModelingSubmission } from 'app/shared/model/modeling-submission.model'; - -describe('Component Tests', () => { - describe('ModelingSubmission Management Update Component', () => { - let comp: ModelingSubmissionUpdateComponent; - let fixture: ComponentFixture; - let service: ModelingSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingSubmissionUpdateComponent], - }) - .overrideTemplate(ModelingSubmissionUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ModelingSubmissionUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingSubmissionService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new ModelingSubmission(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.modelingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new ModelingSubmission(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.modelingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission.component.spec.ts b/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission.component.spec.ts deleted file mode 100644 index 290daa2c87da..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission.component.spec.ts +++ /dev/null @@ -1,56 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ModelingSubmissionComponent } from 'app/exercises/modeling-submission/modeling-submission.component'; -import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; -import { ModelingSubmission } from 'app/shared/model/modeling-submission.model'; -import * as chai from 'chai'; -import * as sinonChai from 'sinon-chai'; - -chai.use(sinonChai); -const expect = chai.expect; - -describe('Component Tests', () => { - describe('ModelingSubmission Management Component', () => { - let comp: ModelingSubmissionComponent; - let fixture: ComponentFixture; - let service: ModelingSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ModelingSubmissionComponent], - providers: [], - }) - .overrideTemplate(ModelingSubmissionComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ModelingSubmissionComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ModelingSubmissionService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new ModelingSubmission(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.modelingSubmissions[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission.service.spec.ts b/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission.service.spec.ts deleted file mode 100644 index b58981c1552e..000000000000 --- a/src/test/javascript/spec/app/entities/modeling-submission/modeling-submission.service.spec.ts +++ /dev/null @@ -1,104 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; -import { IModelingSubmission, ModelingSubmission } from 'app/shared/model/modeling-submission.model'; - -describe('Service Tests', () => { - describe('ModelingSubmission Service', () => { - let injector: TestBed; - let service: ModelingSubmissionService; - let httpMock: HttpTestingController; - let elemDefault: IModelingSubmission; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(ModelingSubmissionService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new ModelingSubmission(0, 'AAAAAAA', 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a ModelingSubmission', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new ModelingSubmission(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a ModelingSubmission', async () => { - const returnedFromService = Object.assign( - { - model: 'BBBBBB', - explanationText: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of ModelingSubmission', async () => { - const returnedFromService = Object.assign( - { - model: 'BBBBBB', - explanationText: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a ModelingSubmission', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/participation/participation-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/participation/participation-delete-dialog.component.spec.ts deleted file mode 100644 index 3ba8fbb0f737..000000000000 --- a/src/test/javascript/spec/app/entities/participation/participation-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ParticipationDeleteDialogComponent } from 'app/exercises/shared/participation/participation-delete-dialog.component'; -import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; - -describe('Component Tests', () => { - describe('Participation Management Delete Component', () => { - let comp: ParticipationDeleteDialogComponent; - let fixture: ComponentFixture; - let service: ParticipationService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ParticipationDeleteDialogComponent], - }) - .overrideTemplate(ParticipationDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ParticipationDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ParticipationService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/participation/participation-detail.component.spec.ts b/src/test/javascript/spec/app/entities/participation/participation-detail.component.spec.ts deleted file mode 100644 index 4aab6ab7ed2c..000000000000 --- a/src/test/javascript/spec/app/entities/participation/participation-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ParticipationDetailComponent } from 'app/exercises/shared/participation/participation-detail.component'; -import { Participation } from 'app/shared/model/participation.model'; - -describe('Component Tests', () => { - describe('Participation Management Detail Component', () => { - let comp: ParticipationDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ participation: new Participation(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ParticipationDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(ParticipationDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ParticipationDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.participation).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/participation/participation-update.component.spec.ts b/src/test/javascript/spec/app/entities/participation/participation-update.component.spec.ts deleted file mode 100644 index 1fe2cce8d587..000000000000 --- a/src/test/javascript/spec/app/entities/participation/participation-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ParticipationUpdateComponent } from 'app/exercises/shared/participation/participation-update.component'; -import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; -import { Participation } from 'app/shared/model/participation.model'; - -describe('Component Tests', () => { - describe('Participation Management Update Component', () => { - let comp: ParticipationUpdateComponent; - let fixture: ComponentFixture; - let service: ParticipationService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ParticipationUpdateComponent], - }) - .overrideTemplate(ParticipationUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ParticipationUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ParticipationService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new Participation(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.participation = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new Participation(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.participation = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/participation/participation.component.spec.ts b/src/test/javascript/spec/app/entities/participation/participation.component.spec.ts deleted file mode 100644 index eb78f496a12f..000000000000 --- a/src/test/javascript/spec/app/entities/participation/participation.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ParticipationComponent } from 'app/exercises/shared/participation/participation.component'; -import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; -import { Participation } from 'app/shared/model/participation.model'; - -describe('Component Tests', () => { - describe('Participation Management Component', () => { - let comp: ParticipationComponent; - let fixture: ComponentFixture; - let service: ParticipationService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ParticipationComponent], - providers: [], - }) - .overrideTemplate(ParticipationComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ParticipationComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ParticipationService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new Participation(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.participations[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/participation/participation.service.spec.ts b/src/test/javascript/spec/app/entities/participation/participation.service.spec.ts deleted file mode 100644 index 11dd3a5d4cc6..000000000000 --- a/src/test/javascript/spec/app/entities/participation/participation.service.spec.ts +++ /dev/null @@ -1,135 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import * as moment from 'moment'; -import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; -import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; -import { InitializationState, IParticipation, Participation } from 'app/shared/model/participation.model'; - -describe('Service Tests', () => { - describe('Participation Service', () => { - let injector: TestBed; - let service: ParticipationService; - let httpMock: HttpTestingController; - let elemDefault: IParticipation; - let currentDate: moment.Moment; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(ParticipationService); - httpMock = injector.get(HttpTestingController); - currentDate = moment(); - - elemDefault = new Participation(0, 'AAAAAAA', 'AAAAAAA', InitializationState.UNINITIALIZED, currentDate, 0); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign( - { - initializationDate: currentDate.format(DATE_TIME_FORMAT), - }, - elemDefault, - ); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a Participation', async () => { - const returnedFromService = Object.assign( - { - id: 0, - initializationDate: currentDate.format(DATE_TIME_FORMAT), - }, - elemDefault, - ); - const expected = Object.assign( - { - initializationDate: currentDate, - }, - returnedFromService, - ); - service - .create(new Participation(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a Participation', async () => { - const returnedFromService = Object.assign( - { - repositoryUrl: 'BBBBBB', - buildPlanId: 'BBBBBB', - initializationState: 'BBBBBB', - initializationDate: currentDate.format(DATE_TIME_FORMAT), - presentationScore: 1, - }, - elemDefault, - ); - - const expected = Object.assign( - { - initializationDate: currentDate, - }, - returnedFromService, - ); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of Participation', async () => { - const returnedFromService = Object.assign( - { - repositoryUrl: 'BBBBBB', - buildPlanId: 'BBBBBB', - initializationState: 'BBBBBB', - initializationDate: currentDate.format(DATE_TIME_FORMAT), - presentationScore: 1, - }, - elemDefault, - ); - const expected = Object.assign( - { - initializationDate: currentDate, - }, - returnedFromService, - ); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a Participation', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-delete-dialog.component.spec.ts deleted file mode 100644 index 8f7403d23d7d..000000000000 --- a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ProgrammingExerciseDeleteDialogComponent } from 'app/entities/programming-exercise/programming-exercise-delete-dialog.component'; -import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; - -describe('Component Tests', () => { - describe('ProgrammingExercise Management Delete Component', () => { - let comp: ProgrammingExerciseDeleteDialogComponent; - let fixture: ComponentFixture; - let service: ProgrammingExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ProgrammingExerciseDeleteDialogComponent], - }) - .overrideTemplate(ProgrammingExerciseDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ProgrammingExerciseDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-detail.component.spec.ts b/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-detail.component.spec.ts deleted file mode 100644 index 8e16b674c650..000000000000 --- a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ProgrammingExerciseDetailComponent } from 'app/exercises/programming/manage/programming-exercise-detail.component'; -import { ProgrammingExercise } from 'app/shared/model/programming-exercise.model'; - -describe('Component Tests', () => { - describe('ProgrammingExercise Management Detail Component', () => { - let comp: ProgrammingExerciseDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ programmingExercise: new ProgrammingExercise(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ProgrammingExerciseDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(ProgrammingExerciseDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ProgrammingExerciseDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.programmingExercise).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-update.component.spec.ts b/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-update.component.spec.ts deleted file mode 100644 index 905c2ee7cc6c..000000000000 --- a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ProgrammingExerciseUpdateComponent } from 'app/exercises/programming/manage/update/programming-exercise-update.component'; -import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; -import { ProgrammingExercise } from 'app/shared/model/programming-exercise.model'; - -describe('Component Tests', () => { - describe('ProgrammingExercise Management Update Component', () => { - let comp: ProgrammingExerciseUpdateComponent; - let fixture: ComponentFixture; - let service: ProgrammingExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ProgrammingExerciseUpdateComponent], - }) - .overrideTemplate(ProgrammingExerciseUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ProgrammingExerciseUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingExerciseService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new ProgrammingExercise(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.programmingExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new ProgrammingExercise(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.programmingExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise.component.spec.ts b/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise.component.spec.ts deleted file mode 100644 index c7f810ea1bb4..000000000000 --- a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ProgrammingExerciseComponent } from 'app/exercises/programming/manage/programming-exercise.component'; -import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; -import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; - -describe('Component Tests', () => { - describe('ProgrammingExercise Management Component', () => { - let comp: ProgrammingExerciseComponent; - let fixture: ComponentFixture; - let service: ProgrammingExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ProgrammingExerciseComponent], - providers: [], - }) - .overrideTemplate(ProgrammingExerciseComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ProgrammingExerciseComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingExerciseService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new ProgrammingExercise(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.programmingExercises[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise.service.spec.ts b/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise.service.spec.ts deleted file mode 100644 index 6d2f86852dda..000000000000 --- a/src/test/javascript/spec/app/entities/programming-exercise/programming-exercise.service.spec.ts +++ /dev/null @@ -1,110 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; -import { IProgrammingExercise, ProgrammingExercise } from 'app/shared/model/programming-exercise.model'; - -describe('Service Tests', () => { - describe('ProgrammingExercise Service', () => { - let injector: TestBed; - let service: ProgrammingExerciseService; - let httpMock: HttpTestingController; - let elemDefault: IProgrammingExercise; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(ProgrammingExerciseService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new ProgrammingExercise(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', false, false); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a ProgrammingExercise', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new ProgrammingExercise(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a ProgrammingExercise', async () => { - const returnedFromService = Object.assign( - { - templateRepositoryUrl: 'BBBBBB', - solutionRepositoryUrl: 'BBBBBB', - templateBuildPlanId: 'BBBBBB', - publishBuildPlanUrl: true, - allowOnlineEditor: true, - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of ProgrammingExercise', async () => { - const returnedFromService = Object.assign( - { - templateRepositoryUrl: 'BBBBBB', - solutionRepositoryUrl: 'BBBBBB', - templateBuildPlanId: 'BBBBBB', - publishBuildPlanUrl: true, - allowOnlineEditor: true, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a ProgrammingExercise', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/programming-submission/programming-submission-delete-dialog.component.spec.ts deleted file mode 100644 index f38dd9d272cf..000000000000 --- a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { ProgrammingSubmissionDeleteDialogComponent } from 'app/entities/programming-submission/programming-submission-delete-dialog.component'; -import { ProgrammingSubmissionService } from 'app/entities/programming-submission/programming-submission.service'; - -describe('Component Tests', () => { - describe('ProgrammingSubmission Management Delete Component', () => { - let comp: ProgrammingSubmissionDeleteDialogComponent; - let fixture: ComponentFixture; - let service: ProgrammingSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [ProgrammingSubmissionDeleteDialogComponent], - }) - .overrideTemplate(ProgrammingSubmissionDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ProgrammingSubmissionDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-detail.component.spec.ts b/src/test/javascript/spec/app/entities/programming-submission/programming-submission-detail.component.spec.ts deleted file mode 100644 index bd470baa90c3..000000000000 --- a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { ProgrammingSubmissionDetailComponent } from 'app/entities/programming-submission/programming-submission-detail.component'; -import { ProgrammingSubmission } from 'app/shared/model/programming-submission.model'; - -describe('Component Tests', () => { - describe('ProgrammingSubmission Management Detail Component', () => { - let comp: ProgrammingSubmissionDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ programmingSubmission: new ProgrammingSubmission(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [ProgrammingSubmissionDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(ProgrammingSubmissionDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ProgrammingSubmissionDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.programmingSubmission).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/programming-submission/programming-submission-dialog.component.spec.ts deleted file mode 100644 index 05fe8bccb122..000000000000 --- a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ProgrammingSubmissionDialogComponent } from '../../../../../../main/webapp/app/entities/programming-submission/programming-submission-dialog.component'; -import { ProgrammingSubmissionService } from '../../../../../../main/webapp/app/entities/programming-submission/programming-submission.service'; -import { ProgrammingSubmission } from 'app/entities/programming-submission.model'; - -describe('Component Tests', () => { - describe('ProgrammingSubmission Management Dialog Component', () => { - let comp: ProgrammingSubmissionDialogComponent; - let fixture: ComponentFixture; - let service: ProgrammingSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ProgrammingSubmissionDialogComponent], - providers: [ProgrammingSubmissionService], - }) - .overrideTemplate(ProgrammingSubmissionDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(ProgrammingSubmissionDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new ProgrammingSubmission(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.programmingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'programmingSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new ProgrammingSubmission(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.programmingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'programmingSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-update.component.spec.ts b/src/test/javascript/spec/app/entities/programming-submission/programming-submission-update.component.spec.ts deleted file mode 100644 index 89b539831eef..000000000000 --- a/src/test/javascript/spec/app/entities/programming-submission/programming-submission-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { ProgrammingSubmissionUpdateComponent } from 'app/entities/programming-submission/programming-submission-update.component'; -import { ProgrammingSubmissionService } from 'app/entities/programming-submission/programming-submission.service'; -import { ProgrammingSubmission } from 'app/shared/model/programming-submission.model'; - -describe('Component Tests', () => { - describe('ProgrammingSubmission Management Update Component', () => { - let comp: ProgrammingSubmissionUpdateComponent; - let fixture: ComponentFixture; - let service: ProgrammingSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [ProgrammingSubmissionUpdateComponent], - }) - .overrideTemplate(ProgrammingSubmissionUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ProgrammingSubmissionUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingSubmissionService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new ProgrammingSubmission(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.programmingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new ProgrammingSubmission(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.programmingSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-submission/programming-submission.component.spec.ts b/src/test/javascript/spec/app/entities/programming-submission/programming-submission.component.spec.ts deleted file mode 100644 index b70e58b8e222..000000000000 --- a/src/test/javascript/spec/app/entities/programming-submission/programming-submission.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { ProgrammingSubmissionComponent } from 'app/entities/programming-submission/programming-submission.component'; -import { ProgrammingSubmissionService } from 'app/entities/programming-submission/programming-submission.service'; -import { ProgrammingSubmission } from 'app/shared/model/programming-submission.model'; - -describe('Component Tests', () => { - describe('ProgrammingSubmission Management Component', () => { - let comp: ProgrammingSubmissionComponent; - let fixture: ComponentFixture; - let service: ProgrammingSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [ProgrammingSubmissionComponent], - providers: [], - }) - .overrideTemplate(ProgrammingSubmissionComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ProgrammingSubmissionComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ProgrammingSubmissionService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new ProgrammingSubmission(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.programmingSubmissions[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/programming-submission/programming-submission.service.spec.ts b/src/test/javascript/spec/app/entities/programming-submission/programming-submission.service.spec.ts deleted file mode 100644 index b4227c3c5b9c..000000000000 --- a/src/test/javascript/spec/app/entities/programming-submission/programming-submission.service.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { ProgrammingSubmissionService } from 'app/entities/programming-submission/programming-submission.service'; -import { IProgrammingSubmission, ProgrammingSubmission } from 'app/shared/model/programming-submission.model'; - -describe('Service Tests', () => { - describe('ProgrammingSubmission Service', () => { - let injector: TestBed; - let service: ProgrammingSubmissionService; - let httpMock: HttpTestingController; - let elemDefault: IProgrammingSubmission; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(ProgrammingSubmissionService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new ProgrammingSubmission(0, 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a ProgrammingSubmission', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new ProgrammingSubmission(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a ProgrammingSubmission', async () => { - const returnedFromService = Object.assign( - { - commitHash: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of ProgrammingSubmission', async () => { - const returnedFromService = Object.assign( - { - commitHash: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a ProgrammingSubmission', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-delete-dialog.component.spec.ts deleted file mode 100644 index 0dabc2604f78..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizExerciseDeleteDialogComponent } from 'app/entities/quiz-exercise/quiz-exercise-delete-dialog.component'; -import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; - -describe('Component Tests', () => { - describe('QuizExercise Management Delete Component', () => { - let comp: QuizExerciseDeleteDialogComponent; - let fixture: ComponentFixture; - let service: QuizExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizExerciseDeleteDialogComponent], - }) - .overrideTemplate(QuizExerciseDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(QuizExerciseDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-detail.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-detail.component.spec.ts deleted file mode 100644 index f44e8baba56e..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizExerciseDetailComponent } from 'app/entities/quiz-exercise/quiz-exercise-detail.component'; -import { QuizExercise } from 'app/shared/model/quiz-exercise.model'; - -describe('Component Tests', () => { - describe('QuizExercise Management Detail Component', () => { - let comp: QuizExerciseDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ quizExercise: new QuizExercise(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizExerciseDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(QuizExerciseDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(QuizExerciseDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.quizExercise).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-update.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-update.component.spec.ts deleted file mode 100644 index 49c91cfec755..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizExerciseUpdateComponent } from 'app/entities/quiz-exercise/quiz-exercise-update.component'; -import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; -import { QuizExercise } from 'app/shared/model/quiz-exercise.model'; - -describe('Component Tests', () => { - describe('QuizExercise Management Update Component', () => { - let comp: QuizExerciseUpdateComponent; - let fixture: ComponentFixture; - let service: QuizExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizExerciseUpdateComponent], - }) - .overrideTemplate(QuizExerciseUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(QuizExerciseUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizExerciseService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new QuizExercise(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.quizExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new QuizExercise(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.quizExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise.component.spec.ts deleted file mode 100644 index 4b2a5a5701d6..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizExerciseComponent } from 'app/entities/quiz-exercise/quiz-exercise.component'; -import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; -import { QuizExercise } from 'app/shared/model/quiz-exercise.model'; - -describe('Component Tests', () => { - describe('QuizExercise Management Component', () => { - let comp: QuizExerciseComponent; - let fixture: ComponentFixture; - let service: QuizExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizExerciseComponent], - providers: [], - }) - .overrideTemplate(QuizExerciseComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(QuizExerciseComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizExerciseService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new QuizExercise(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.quizExercises[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise.service.spec.ts b/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise.service.spec.ts deleted file mode 100644 index d98e568239b8..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-exercise/quiz-exercise.service.spec.ts +++ /dev/null @@ -1,116 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; -import { IQuizExercise, QuizExercise } from 'app/shared/model/quiz-exercise.model'; - -describe('Service Tests', () => { - describe('QuizExercise Service', () => { - let injector: TestBed; - let service: QuizExerciseService; - let httpMock: HttpTestingController; - let elemDefault: IQuizExercise; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(QuizExerciseService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new QuizExercise(0, 'AAAAAAA', 'AAAAAAA', false, 0, false, false, false, 0); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a QuizExercise', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new QuizExercise(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a QuizExercise', async () => { - const returnedFromService = Object.assign( - { - description: 'BBBBBB', - explanation: 'BBBBBB', - randomizeQuestionOrder: true, - allowedNumberOfAttempts: 1, - isVisibleBeforeStart: true, - isOpenForPractice: true, - isPlannedToStart: true, - duration: 1, - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of QuizExercise', async () => { - const returnedFromService = Object.assign( - { - description: 'BBBBBB', - explanation: 'BBBBBB', - randomizeQuestionOrder: true, - allowedNumberOfAttempts: 1, - isVisibleBeforeStart: true, - isOpenForPractice: true, - isPlannedToStart: true, - duration: 1, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a QuizExercise', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-delete-dialog.component.spec.ts deleted file mode 100644 index e720b6110ede..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizSubmissionDeleteDialogComponent } from 'app/exercises/quiz/participate/quiz-submission/quiz-submission-delete-dialog.component'; -import { QuizParticipationService } from 'app/exercises/quiz/participate/quiz-participation.service'; - -describe('Component Tests', () => { - describe('QuizSubmission Management Delete Component', () => { - let comp: QuizSubmissionDeleteDialogComponent; - let fixture: ComponentFixture; - let service: QuizParticipationService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizSubmissionDeleteDialogComponent], - }) - .overrideTemplate(QuizSubmissionDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(QuizSubmissionDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizParticipationService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-detail.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-detail.component.spec.ts deleted file mode 100644 index 23fa4ad27cfb..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizSubmissionDetailComponent } from 'app/exercises/quiz/participate/quiz-submission/quiz-submission-detail.component'; -import { QuizSubmission } from 'app/shared/model/quiz-submission.model'; - -describe('Component Tests', () => { - describe('QuizSubmission Management Detail Component', () => { - let comp: QuizSubmissionDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ quizSubmission: new QuizSubmission(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizSubmissionDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(QuizSubmissionDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(QuizSubmissionDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.quizSubmission).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-dialog.component.spec.ts deleted file mode 100644 index a32738fad270..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizSubmissionDialogComponent } from '../../../../../../main/webapp/app/exercises/quiz/participate/quiz-submission/quiz-submission-dialog.component'; -import { QuizParticipationService } from 'app/exercises/quiz/participate/quiz-participation.service'; -import { QuizSubmission } from 'app/entities/quiz/quiz-submission.model'; - -describe('Component Tests', () => { - describe('QuizSubmission Management Dialog Component', () => { - let comp: QuizSubmissionDialogComponent; - let fixture: ComponentFixture; - let service: QuizParticipationService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizSubmissionDialogComponent], - providers: [QuizParticipationService], - }) - .overrideTemplate(QuizSubmissionDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(QuizSubmissionDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizParticipationService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new QuizSubmission(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.quizSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'quizSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new QuizSubmission(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.quizSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'quizSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-update.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-update.component.spec.ts deleted file mode 100644 index 526bac63c049..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizSubmissionUpdateComponent } from 'app/exercises/quiz/participate/quiz-submission/quiz-submission-update.component'; -import { QuizParticipationService } from 'app/exercises/quiz/participate/quiz-participation.service'; -import { QuizSubmission } from 'app/shared/model/quiz-submission.model'; - -describe('Component Tests', () => { - describe('QuizSubmission Management Update Component', () => { - let comp: QuizSubmissionUpdateComponent; - let fixture: ComponentFixture; - let service: QuizParticipationService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizSubmissionUpdateComponent], - }) - .overrideTemplate(QuizSubmissionUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(QuizSubmissionUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizParticipationService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new QuizSubmission(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.quizSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new QuizSubmission(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.quizSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission.component.spec.ts b/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission.component.spec.ts deleted file mode 100644 index d65b205622ea..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArtemisTestModule } from '../../../test.module'; -import { QuizSubmissionComponent } from 'app/exercises/quiz/participate/quiz-submission/quiz-submission.component'; -import { QuizParticipationService } from 'app/exercises/quiz/participate/quiz-participation.service'; -import { QuizSubmission } from 'app/shared/model/quiz-submission.model'; - -describe('Component Tests', () => { - describe('QuizSubmission Management Component', () => { - let comp: QuizSubmissionComponent; - let fixture: ComponentFixture; - let service: QuizParticipationService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [QuizSubmissionComponent], - providers: [], - }) - .overrideTemplate(QuizSubmissionComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(QuizSubmissionComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(QuizParticipationService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new QuizSubmission(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.quizSubmissions[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission.service.spec.ts b/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission.service.spec.ts deleted file mode 100644 index bb8f2e7cf63b..000000000000 --- a/src/test/javascript/spec/app/entities/quiz-submission/quiz-submission.service.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { QuizParticipationService } from 'app/exercises/quiz/participate/quiz-participation.service'; -import { IQuizSubmission, QuizSubmission } from 'app/shared/model/quiz-submission.model'; - -describe('Service Tests', () => { - describe('QuizSubmission Service', () => { - let injector: TestBed; - let service: QuizParticipationService; - let httpMock: HttpTestingController; - let elemDefault: IQuizSubmission; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(QuizParticipationService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new QuizSubmission(0, 0); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a QuizSubmission', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new QuizSubmission(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a QuizSubmission', async () => { - const returnedFromService = Object.assign( - { - scoreInPoints: 1, - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of QuizSubmission', async () => { - const returnedFromService = Object.assign( - { - scoreInPoints: 1, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a QuizSubmission', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/result/result-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/result/result-dialog.component.spec.ts deleted file mode 100644 index 2ad933da7db9..000000000000 --- a/src/test/javascript/spec/app/entities/result/result-dialog.component.spec.ts +++ /dev/null @@ -1,81 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { ResultDialogComponent } from '../../../../../../main/webapp/app/exercises/shared/result/result-dialog.component'; -import { ResultService } from '../../../../../../main/webapp/app/exercises/shared/result/result.service'; -import { Result } from 'app/entities/result.model'; -import { SubmissionService } from '../../../../../../main/webapp/app/exercises/shared/submission'; -import { ParticipationService } from '../../../../../../main/webapp/app/exercises/shared/participation'; - -describe('Component Tests', () => { - describe('Result Management Dialog Component', () => { - let comp: ResultDialogComponent; - let fixture: ComponentFixture; - let service: ResultService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ResultDialogComponent], - providers: [SubmissionService, ParticipationService, ResultService], - }) - .overrideTemplate(ResultDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(ResultDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ResultService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new Result(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.result = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'resultListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new Result(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.result = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'resultListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/text-exercise/text-exercise-delete-dialog.component.spec.ts deleted file mode 100644 index 14b48c9cceb1..000000000000 --- a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextExerciseDeleteDialogComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-delete-dialog.component'; -import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; - -describe('Component Tests', () => { - describe('TextExercise Management Delete Component', () => { - let comp: TextExerciseDeleteDialogComponent; - let fixture: ComponentFixture; - let service: TextExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextExerciseDeleteDialogComponent], - }) - .overrideTemplate(TextExerciseDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(TextExerciseDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-detail.component.spec.ts b/src/test/javascript/spec/app/entities/text-exercise/text-exercise-detail.component.spec.ts deleted file mode 100644 index 22b6b2ede930..000000000000 --- a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextExerciseDetailComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-detail.component'; -import { TextExercise } from 'app/shared/model/text-exercise.model'; - -describe('Component Tests', () => { - describe('TextExercise Management Detail Component', () => { - let comp: TextExerciseDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ textExercise: new TextExercise(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextExerciseDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(TextExerciseDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(TextExerciseDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.textExercise).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/text-exercise/text-exercise-dialog.component.spec.ts deleted file mode 100644 index f08bf75a6cd1..000000000000 --- a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { TextExerciseDialogComponent } from '../../../../../../main/webapp/app/exercises/text/manage/text-exercise/text-exercise-dialog.component'; -import { TextExerciseService } from '../../../../../../main/webapp/app/exercises/text/manage/text-exercise/text-exercise.service'; -import { TextExercise } from 'app/entities/text-exercise.model'; - -describe('Component Tests', () => { - describe('TextExercise Management Dialog Component', () => { - let comp: TextExerciseDialogComponent; - let fixture: ComponentFixture; - let service: TextExerciseService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [TextExerciseDialogComponent], - providers: [TextExerciseService], - }) - .overrideTemplate(TextExerciseDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(TextExerciseDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextExerciseService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new TextExercise(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.textExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'textExerciseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new TextExercise(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.textExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'textExerciseListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-update.component.spec.ts b/src/test/javascript/spec/app/entities/text-exercise/text-exercise-update.component.spec.ts deleted file mode 100644 index 0820c194199b..000000000000 --- a/src/test/javascript/spec/app/entities/text-exercise/text-exercise-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextExerciseUpdateComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-update.component'; -import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; -import { TextExercise } from 'app/shared/model/text-exercise.model'; - -describe('Component Tests', () => { - describe('TextExercise Management Update Component', () => { - let comp: TextExerciseUpdateComponent; - let fixture: ComponentFixture; - let service: TextExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextExerciseUpdateComponent], - }) - .overrideTemplate(TextExerciseUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(TextExerciseUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextExerciseService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new TextExercise(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.textExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new TextExercise(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.textExercise = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-exercise/text-exercise.component.spec.ts b/src/test/javascript/spec/app/entities/text-exercise/text-exercise.component.spec.ts deleted file mode 100644 index 1074a449e0ee..000000000000 --- a/src/test/javascript/spec/app/entities/text-exercise/text-exercise.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextExerciseComponent } from 'app/exercises/text/manage/text-exercise/text-exercise.component'; -import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; -import { TextExercise } from 'app/shared/model/text-exercise.model'; - -describe('Component Tests', () => { - describe('TextExercise Management Component', () => { - let comp: TextExerciseComponent; - let fixture: ComponentFixture; - let service: TextExerciseService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextExerciseComponent], - providers: [], - }) - .overrideTemplate(TextExerciseComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(TextExerciseComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextExerciseService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new TextExercise(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.textExercises[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-exercise/text-exercise.service.spec.ts b/src/test/javascript/spec/app/entities/text-exercise/text-exercise.service.spec.ts deleted file mode 100644 index 8a9fc32dc765..000000000000 --- a/src/test/javascript/spec/app/entities/text-exercise/text-exercise.service.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; -import { ITextExercise, TextExercise } from 'app/shared/model/text-exercise.model'; - -describe('Service Tests', () => { - describe('TextExercise Service', () => { - let injector: TestBed; - let service: TextExerciseService; - let httpMock: HttpTestingController; - let elemDefault: ITextExercise; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(TextExerciseService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new TextExercise(0, 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a TextExercise', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new TextExercise(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a TextExercise', async () => { - const returnedFromService = Object.assign( - { - sampleSolution: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of TextExercise', async () => { - const returnedFromService = Object.assign( - { - sampleSolution: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a TextExercise', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-submission/text-submission-delete-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/text-submission/text-submission-delete-dialog.component.spec.ts deleted file mode 100644 index 17796a19ac31..000000000000 --- a/src/test/javascript/spec/app/entities/text-submission/text-submission-delete-dialog.component.spec.ts +++ /dev/null @@ -1,52 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { of } from 'rxjs'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextSubmissionDeleteDialogComponent } from 'app/exercises/text/participate/text-submission/text-submission-delete-dialog.component'; -import { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service'; - -describe('Component Tests', () => { - describe('TextSubmission Management Delete Component', () => { - let comp: TextSubmissionDeleteDialogComponent; - let fixture: ComponentFixture; - let service: TextSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextSubmissionDeleteDialogComponent], - }) - .overrideTemplate(TextSubmissionDeleteDialogComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(TextSubmissionDeleteDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('confirmDelete', () => { - it('Should call delete service on confirmDelete', inject( - [], - fakeAsync(() => { - // GIVEN - spyOn(service, 'delete').and.returnValue(of({})); - - // WHEN - comp.confirmDelete(123); - tick(); - - // THEN - expect(service.delete).toHaveBeenCalledWith(123); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - expect(mockEventManager.broadcastSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-submission/text-submission-detail.component.spec.ts b/src/test/javascript/spec/app/entities/text-submission/text-submission-detail.component.spec.ts deleted file mode 100644 index 7a9c3f53bbab..000000000000 --- a/src/test/javascript/spec/app/entities/text-submission/text-submission-detail.component.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { ActivatedRoute } from '@angular/router'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextSubmissionDetailComponent } from 'app/exercises/text/participate/text-submission/text-submission-detail.component'; -import { TextSubmission } from 'app/shared/model/text-submission.model'; - -describe('Component Tests', () => { - describe('TextSubmission Management Detail Component', () => { - let comp: TextSubmissionDetailComponent; - let fixture: ComponentFixture; - const route = ({ data: of({ textSubmission: new TextSubmission(123) }) } as any) as ActivatedRoute; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextSubmissionDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(TextSubmissionDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(TextSubmissionDetailComponent); - comp = fixture.componentInstance; - }); - - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN - - // WHEN - comp.ngOnInit(); - - // THEN - expect(comp.textSubmission).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-submission/text-submission-dialog.component.spec.ts b/src/test/javascript/spec/app/entities/text-submission/text-submission-dialog.component.spec.ts deleted file mode 100644 index 1e0db7339b3c..000000000000 --- a/src/test/javascript/spec/app/entities/text-submission/text-submission-dialog.component.spec.ts +++ /dev/null @@ -1,79 +0,0 @@ -/* tslint:disable max-line-length */ -import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; -import { Observable } from 'rxjs/Observable'; -import { JhiEventManager } from 'ng-jhipster'; - -import { ArtemisTestModule } from '../../../test.module'; -import { TextSubmissionDialogComponent } from '../../../../../../main/webapp/app/exercises/text/participate/text-submission/text-submission-dialog.component'; -import { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service'; -import { TextSubmission } from 'app/entities/text-submission.model'; - -describe('Component Tests', () => { - describe('TextSubmission Management Dialog Component', () => { - let comp: TextSubmissionDialogComponent; - let fixture: ComponentFixture; - let service: TextSubmissionService; - let mockEventManager: any; - let mockActiveModal: any; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [TextSubmissionDialogComponent], - providers: [TextSubmissionService], - }) - .overrideTemplate(TextSubmissionDialogComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(TextSubmissionDialogComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextSubmissionService); - mockEventManager = fixture.debugElement.injector.get(JhiEventManager); - mockActiveModal = fixture.debugElement.injector.get(NgbActiveModal); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new TextSubmission(123); - spyOn(service, 'update').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.textSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'textSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - - it('Should call create service on save for new entity', inject( - [], - fakeAsync(() => { - // GIVEN - const entity = new TextSubmission(); - spyOn(service, 'create').and.returnValue(Observable.of(new HttpResponse({ body: entity }))); - comp.textSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - expect(mockEventManager.broadcastSpy).toHaveBeenCalledWith({ name: 'textSubmissionListModification', content: 'OK' }); - expect(mockActiveModal.dismissSpy).toHaveBeenCalled(); - }), - )); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-submission/text-submission-update.component.spec.ts b/src/test/javascript/spec/app/entities/text-submission/text-submission-update.component.spec.ts deleted file mode 100644 index e26d3dd9d67c..000000000000 --- a/src/test/javascript/spec/app/entities/text-submission/text-submission-update.component.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { HttpResponse } from '@angular/common/http'; -import { of } from 'rxjs'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextSubmissionUpdateComponent } from 'app/exercises/text/participate/text-submission/text-submission-update.component'; -import { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service'; -import { TextSubmission } from 'app/shared/model/text-submission.model'; - -describe('Component Tests', () => { - describe('TextSubmission Management Update Component', () => { - let comp: TextSubmissionUpdateComponent; - let fixture: ComponentFixture; - let service: TextSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextSubmissionUpdateComponent], - }) - .overrideTemplate(TextSubmissionUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(TextSubmissionUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextSubmissionService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new TextSubmission(123); - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.textSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new TextSubmission(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.textSubmission = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-submission/text-submission.component.spec.ts b/src/test/javascript/spec/app/entities/text-submission/text-submission.component.spec.ts deleted file mode 100644 index f8f701ea495f..000000000000 --- a/src/test/javascript/spec/app/entities/text-submission/text-submission.component.spec.ts +++ /dev/null @@ -1,51 +0,0 @@ -/* tslint:disable max-line-length */ -import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { of } from 'rxjs'; -import { HttpHeaders, HttpResponse } from '@angular/common/http'; - -import { ArTeMiSTestModule } from '../../../test.module'; -import { TextSubmissionComponent } from 'app/exercises/text/participate/text-submission/text-submission.component'; -import { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service'; -import { TextSubmission } from 'app/shared/model/text-submission.model'; - -describe('Component Tests', () => { - describe('TextSubmission Management Component', () => { - let comp: TextSubmissionComponent; - let fixture: ComponentFixture; - let service: TextSubmissionService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArTeMiSTestModule], - declarations: [TextSubmissionComponent], - providers: [], - }) - .overrideTemplate(TextSubmissionComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(TextSubmissionComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(TextSubmissionService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - spyOn(service, 'query').and.returnValue( - of( - new HttpResponse({ - body: [new TextSubmission(123)], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.query).toHaveBeenCalled(); - expect(comp.textSubmissions[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); - }); -}); diff --git a/src/test/javascript/spec/app/entities/text-submission/text-submission.service.spec.ts b/src/test/javascript/spec/app/entities/text-submission/text-submission.service.spec.ts deleted file mode 100644 index eeee8fcf355d..000000000000 --- a/src/test/javascript/spec/app/entities/text-submission/text-submission.service.spec.ts +++ /dev/null @@ -1,102 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { map, take } from 'rxjs/operators'; -import { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service'; -import { ITextSubmission, TextSubmission } from 'app/shared/model/text-submission.model'; - -describe('Service Tests', () => { - describe('TextSubmission Service', () => { - let injector: TestBed; - let service: TextSubmissionService; - let httpMock: HttpTestingController; - let elemDefault: ITextSubmission; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - injector = getTestBed(); - service = injector.get(TextSubmissionService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new TextSubmission(0, 'AAAAAAA'); - }); - - describe('Service methods', async () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should create a TextSubmission', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new TextSubmission(null)) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should update a TextSubmission', async () => { - const returnedFromService = Object.assign( - { - text: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(JSON.stringify(returnedFromService)); - }); - - it('should return a list of TextSubmission', async () => { - const returnedFromService = Object.assign( - { - text: 'BBBBBB', - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .query(expected) - .pipe( - take(1), - map((resp) => resp.body), - ) - .subscribe((body) => expect(body).toContainEqual(expected)); - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(JSON.stringify([returnedFromService])); - httpMock.verify(); - }); - - it('should delete a TextSubmission', async () => { - const rxPromise = service.delete(123).subscribe((resp) => expect(resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts b/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts deleted file mode 100644 index 3d0ef70ad9fa..000000000000 --- a/src/test/javascript/spec/app/shared/alert/alert-error.component.spec.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { async, ComponentFixture, TestBed } from '@angular/core/testing'; -import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; -import { JhiEventManager } from 'ng-jhipster'; -import { TranslateModule } from '@ngx-translate/core'; - -import { ArtemisTestModule } from '../../../test.module'; -import { AlertErrorComponent } from 'app/shared/alert/alert-error.component'; -import { MockAlertService } from '../../../helpers/mock-alert.service'; -import { AlertService } from 'app/core/alert/alert.service'; - -describe('Component Tests', () => { - describe('Alert Error Component', () => { - let comp: AlertErrorComponent; - let fixture: ComponentFixture; - let eventManager: JhiEventManager; - - beforeEach(async(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule, TranslateModule.forRoot()], - declarations: [AlertErrorComponent], - providers: [ - JhiEventManager, - { - provide: AlertService, - useClass: MockAlertService, - }, - ], - }) - .overrideTemplate(AlertErrorComponent, '') - .compileComponents(); - })); - - beforeEach(() => { - fixture = TestBed.createComponent(AlertErrorComponent); - comp = fixture.componentInstance; - eventManager = fixture.debugElement.injector.get(JhiEventManager); - }); - - describe('Error Handling', () => { - it('Should display an alert on status 0', () => { - // GIVEN - eventManager.broadcast({ name: 'artemisApp.httpError', content: { status: 0 } }); - // THEN - expect(comp.alerts.length).toBe(1); - expect(comp.alerts[0].msg).toBe('error.server.not.reachable'); - }); - it('Should display an alert on status 404', () => { - // GIVEN - eventManager.broadcast({ name: 'artemisApp.httpError', content: { status: 404 } }); - // THEN - expect(comp.alerts.length).toBe(1); - expect(comp.alerts[0].msg).toBe('error.url.not.found'); - }); - it('Should display an alert on generic error', () => { - // GIVEN - eventManager.broadcast({ name: 'artemisApp.httpError', content: { error: { message: 'Error Message' } } }); - eventManager.broadcast({ name: 'artemisApp.httpError', content: { error: 'Second Error Message' } }); - // THEN - expect(comp.alerts.length).toBe(2); - expect(comp.alerts[0].msg).toBe('Error Message'); - expect(comp.alerts[1].msg).toBe('Second Error Message'); - }); - it('Should display an alert on status 400 for generic error', () => { - // GIVEN - const response = new HttpErrorResponse({ - url: 'http://localhost:8080/api/foos', - headers: new HttpHeaders(), - status: 400, - statusText: 'Bad Request', - error: { - type: 'https://www.jhipster.tech/problem/constraint-violation', - title: 'Bad Request', - status: 400, - path: '/api/foos', - message: 'error.validation', - }, - }); - eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); - // THEN - expect(comp.alerts.length).toBe(1); - expect(comp.alerts[0].msg).toBe('error.validation'); - }); - it('Should display an alert on status 400 for generic error without message', () => { - // GIVEN - const response = new HttpErrorResponse({ - url: 'http://localhost:8080/api/foos', - headers: new HttpHeaders(), - status: 400, - error: 'Bad Request', - }); - eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); - // THEN - expect(comp.alerts.length).toBe(1); - expect(comp.alerts[0].msg).toBe('Bad Request'); - }); - it('Should display an alert on status 400 for invalid parameters', () => { - // GIVEN - const response = new HttpErrorResponse({ - url: 'http://localhost:8080/api/foos', - headers: new HttpHeaders(), - status: 400, - statusText: 'Bad Request', - error: { - type: 'https://www.jhipster.tech/problem/constraint-violation', - title: 'Method argument not valid', - status: 400, - path: '/api/foos', - message: 'error.validation', - fieldErrors: [{ objectName: 'foo', field: 'minField', message: 'Min' }], - }, - }); - eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); - // THEN - expect(comp.alerts.length).toBe(1); - expect(comp.alerts[0].msg).toBe('error.Size'); - }); - it('Should display an alert on status 400 for error headers', () => { - // GIVEN - const response = new HttpErrorResponse({ - url: 'http://localhost:8080/api/foos', - headers: new HttpHeaders().append('app-error', 'Error Message').append('app-params', 'foo'), - status: 400, - statusText: 'Bad Request', - error: { - status: 400, - message: 'error.validation', - }, - }); - eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); - // THEN - expect(comp.alerts.length).toBe(1); - expect(comp.alerts[0].msg).toBe('Error Message'); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/app/shared/user/user.service.spec.ts b/src/test/javascript/spec/app/shared/user/user.service.spec.ts deleted file mode 100644 index a3952c07b9e4..000000000000 --- a/src/test/javascript/spec/app/shared/user/user.service.spec.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { TestBed } from '@angular/core/testing'; -import { JhiDateUtils } from 'ng-jhipster'; - -import { User } from 'app/core/user/user.model'; -import { UserService } from 'app/core/user/user.service'; -import { SERVER_API_URL } from 'app/app.constants'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; - -describe('Service Tests', () => { - describe('User Service', () => { - let service: UserService; - let httpMock: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [JhiDateUtils, UserService], - }); - - service = TestBed.inject(UserService); - httpMock = TestBed.inject(HttpTestingController); - }); - - afterEach(() => { - httpMock.verify(); - }); - - describe('Service methods', () => { - it('should call correct URL', () => { - service.find('user').subscribe(() => {}); - - const req = httpMock.expectOne({ method: 'GET' }); - const resourceUrl = SERVER_API_URL + 'api/users'; - expect(req.request.url).toEqual(`${resourceUrl}/user`); - }); - it('should return User', () => { - service.find('user').subscribe((received) => { - expect(received.body.login).toEqual('user'); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(new User(1, 'user')); - }); - - it('should return Authorities', () => { - service.authorities().subscribe((_authorities) => { - expect(_authorities).toEqual(['ROLE_USER', 'ROLE_ADMIN']); - }); - const req = httpMock.expectOne({ method: 'GET' }); - - req.flush(['ROLE_USER', 'ROLE_ADMIN']); - }); - - it('should propagate not found response', () => { - service.find('user').subscribe(null, (_error: any) => { - expect(_error.status).toEqual(404); - }); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush('Invalid request parameters', { - status: 404, - statusText: 'Bad Request', - }); - }); - }); - }); -}); diff --git a/src/test/javascript/spec/component/account/activate.component.spec.ts b/src/test/javascript/spec/component/account/activate.component.spec.ts new file mode 100644 index 000000000000..d69ad94465f9 --- /dev/null +++ b/src/test/javascript/spec/component/account/activate.component.spec.ts @@ -0,0 +1,70 @@ +import { async, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of, throwError } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route'; +import { ActivateService } from 'app/account/activate/activate.service'; +import { ActivateComponent } from 'app/account/activate/activate.component'; + +describe('ActivateComponent', () => { + let comp: ActivateComponent; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ActivateComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: new MockActivatedRoute({ key: 'ABC123' }), + }, + ], + }) + .overrideTemplate(ActivateComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + const fixture = TestBed.createComponent(ActivateComponent); + comp = fixture.componentInstance; + }); + + it('calls activate.get with the key from params', inject( + [ActivateService], + fakeAsync((service: ActivateService) => { + spyOn(service, 'get').and.returnValue(of()); + + comp.ngOnInit(); + tick(); + + expect(service.get).toHaveBeenCalledWith('ABC123'); + }), + )); + + it('should set set success to OK upon successful activation', inject( + [ActivateService], + fakeAsync((service: ActivateService) => { + spyOn(service, 'get').and.returnValue(of({})); + + comp.ngOnInit(); + tick(); + + expect(comp.error).toBe(null); + expect(comp.success).toEqual('OK'); + }), + )); + + it('should set set error to ERROR upon activation failure', inject( + [ActivateService], + fakeAsync((service: ActivateService) => { + spyOn(service, 'get').and.returnValue(throwError('ERROR')); + + comp.ngOnInit(); + tick(); + + expect(comp.error).toBe('ERROR'); + expect(comp.success).toEqual(null); + }), + )); +}); diff --git a/src/test/javascript/spec/component/account/password-reset-finish.component.spec.ts b/src/test/javascript/spec/component/account/password-reset-finish.component.spec.ts new file mode 100644 index 000000000000..d9a9d6c258c6 --- /dev/null +++ b/src/test/javascript/spec/component/account/password-reset-finish.component.spec.ts @@ -0,0 +1,117 @@ +import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; +import { of, throwError } from 'rxjs'; +import { ElementRef, Renderer2 } from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; + +import { ArtemisTestModule } from '../../test.module'; +import { PasswordResetFinishComponent } from 'app/account/password-reset/finish/password-reset-finish.component'; +import { PasswordResetFinishService } from 'app/account/password-reset/finish/password-reset-finish.service'; +import { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route'; + +describe('PasswordResetFinishComponent', () => { + let fixture: ComponentFixture; + let comp: PasswordResetFinishComponent; + + beforeEach(() => { + fixture = TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [PasswordResetFinishComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: new MockActivatedRoute({ key: 'XYZPDQ' }), + }, + { + provide: Renderer2, + useValue: { + invokeElementMethod() {}, + }, + }, + { + provide: ElementRef, + useValue: new ElementRef(null), + }, + ], + }) + .overrideTemplate(PasswordResetFinishComponent, '') + .createComponent(PasswordResetFinishComponent); + }); + + beforeEach(() => { + fixture = TestBed.createComponent(PasswordResetFinishComponent); + comp = fixture.componentInstance; + comp.ngOnInit(); + }); + + it('should define its initial state', () => { + comp.ngOnInit(); + + expect(comp.keyMissing).toBeFalsy(); + expect(comp.key).toEqual('XYZPDQ'); + expect(comp.resetAccount).toEqual({}); + }); + + it('sets focus after the view has been initialized', inject([ElementRef], (elementRef: ElementRef) => { + const element = fixture.nativeElement; + const node = { + focus() {}, + }; + + elementRef.nativeElement = element; + spyOn(element, 'querySelector').and.returnValue(node); + spyOn(node, 'focus'); + + comp.ngAfterViewInit(); + + expect(element.querySelector).toHaveBeenCalledWith('#password'); + expect(node.focus).toHaveBeenCalled(); + })); + + it('should ensure the two passwords entered match', () => { + comp.resetAccount.password = 'password'; + comp.confirmPassword = 'non-matching'; + + comp.finishReset(); + + expect(comp.doNotMatch).toEqual('ERROR'); + }); + + it('should update success to OK after resetting password', inject( + [PasswordResetFinishService], + fakeAsync((service: PasswordResetFinishService) => { + spyOn(service, 'save').and.returnValue(of({})); + + comp.resetAccount.password = 'password'; + comp.confirmPassword = 'password'; + + comp.finishReset(); + tick(); + + expect(service.save).toHaveBeenCalledWith({ + key: 'XYZPDQ', + newPassword: 'password', + }); + expect(comp.success).toEqual('OK'); + }), + )); + + it('should notify of generic error', inject( + [PasswordResetFinishService], + fakeAsync((service: PasswordResetFinishService) => { + spyOn(service, 'save').and.returnValue(throwError('ERROR')); + + comp.resetAccount.password = 'password'; + comp.confirmPassword = 'password'; + + comp.finishReset(); + tick(); + + expect(service.save).toHaveBeenCalledWith({ + key: 'XYZPDQ', + newPassword: 'password', + }); + expect(comp.success).toBeNull(); + expect(comp.error).toEqual('ERROR'); + }), + )); +}); diff --git a/src/test/javascript/spec/component/account/password-reset-init.component.spec.ts b/src/test/javascript/spec/component/account/password-reset-init.component.spec.ts new file mode 100644 index 000000000000..4ee96cc78c89 --- /dev/null +++ b/src/test/javascript/spec/component/account/password-reset-init.component.spec.ts @@ -0,0 +1,105 @@ +import { ComponentFixture, inject, TestBed } from '@angular/core/testing'; +import { ElementRef, Renderer2 } from '@angular/core'; +import { of, throwError } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { PasswordResetInitComponent } from 'app/account/password-reset/init/password-reset-init.component'; +import { PasswordResetInitService } from 'app/account/password-reset/init/password-reset-init.service'; +import { EMAIL_NOT_FOUND_TYPE } from 'app/shared/constants/error.constants'; + +describe('PasswordResetInitComponent', () => { + let fixture: ComponentFixture; + let comp: PasswordResetInitComponent; + + beforeEach(() => { + fixture = TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [PasswordResetInitComponent], + providers: [ + { + provide: Renderer2, + useValue: { + invokeElementMethod() {}, + }, + }, + { + provide: ElementRef, + useValue: new ElementRef(null), + }, + ], + }) + .overrideTemplate(PasswordResetInitComponent, '') + .createComponent(PasswordResetInitComponent); + comp = fixture.componentInstance; + comp.ngOnInit(); + }); + + it('should define its initial state', () => { + expect(comp.success).toBeUndefined(); + expect(comp.error).toBeUndefined(); + expect(comp.errorEmailNotExists).toBeUndefined(); + expect(comp.resetAccount).toEqual({}); + }); + + it('sets focus after the view has been initialized', inject([ElementRef], (elementRef: ElementRef) => { + const element = fixture.nativeElement; + const node = { + focus() {}, + }; + + elementRef.nativeElement = element; + spyOn(element, 'querySelector').and.returnValue(node); + spyOn(node, 'focus'); + + comp.ngAfterViewInit(); + + expect(element.querySelector).toHaveBeenCalledWith('#email'); + expect(node.focus).toHaveBeenCalled(); + })); + + it('notifies of success upon successful requestReset', inject([PasswordResetInitService], (service: PasswordResetInitService) => { + spyOn(service, 'save').and.returnValue(of({})); + comp.resetAccount.email = 'user@domain.com'; + + comp.requestReset(); + + expect(service.save).toHaveBeenCalledWith('user@domain.com'); + expect(comp.success).toEqual('OK'); + expect(comp.error).toBeNull(); + expect(comp.errorEmailNotExists).toBeNull(); + })); + + it('notifies of unknown email upon email address not registered/400', inject([PasswordResetInitService], (service: PasswordResetInitService) => { + spyOn(service, 'save').and.returnValue( + throwError({ + status: 400, + error: { type: EMAIL_NOT_FOUND_TYPE }, + }), + ); + comp.resetAccount.email = 'user@domain.com'; + + comp.requestReset(); + + expect(service.save).toHaveBeenCalledWith('user@domain.com'); + expect(comp.success).toBeNull(); + expect(comp.error).toBeNull(); + expect(comp.errorEmailNotExists).toEqual('ERROR'); + })); + + it('notifies of error upon error response', inject([PasswordResetInitService], (service: PasswordResetInitService) => { + spyOn(service, 'save').and.returnValue( + throwError({ + status: 503, + data: 'something else', + }), + ); + comp.resetAccount.email = 'user@domain.com'; + + comp.requestReset(); + + expect(service.save).toHaveBeenCalledWith('user@domain.com'); + expect(comp.success).toBeNull(); + expect(comp.errorEmailNotExists).toBeNull(); + expect(comp.error).toEqual('ERROR'); + })); +}); diff --git a/src/test/javascript/spec/component/account/password-strength-bar.component.spec.ts b/src/test/javascript/spec/component/account/password-strength-bar.component.spec.ts new file mode 100644 index 000000000000..1ada36608705 --- /dev/null +++ b/src/test/javascript/spec/component/account/password-strength-bar.component.spec.ts @@ -0,0 +1,46 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; + +import { PasswordStrengthBarComponent } from 'app/account/password/password-strength-bar.component'; + +describe('PasswordStrengthBarComponent', () => { + let comp: PasswordStrengthBarComponent; + let fixture: ComponentFixture; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + declarations: [PasswordStrengthBarComponent], + }) + .overrideTemplate(PasswordStrengthBarComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(PasswordStrengthBarComponent); + comp = fixture.componentInstance; + }); + + describe('PasswordStrengthBarComponents', () => { + it('should initialize with default values', () => { + expect(comp.measureStrength('')).toBe(0); + expect(comp.colors).toEqual(['#F00', '#F90', '#FF0', '#9F0', '#0F0']); + expect(comp.getColor(0).idx).toBe(1); + expect(comp.getColor(0).col).toBe(comp.colors[0]); + }); + + it('should increase strength upon password value change', () => { + expect(comp.measureStrength('')).toBe(0); + expect(comp.measureStrength('aa')).toBeGreaterThanOrEqual(comp.measureStrength('')); + expect(comp.measureStrength('aa^6')).toBeGreaterThanOrEqual(comp.measureStrength('aa')); + expect(comp.measureStrength('Aa090(**)')).toBeGreaterThanOrEqual(comp.measureStrength('aa^6')); + expect(comp.measureStrength('Aa090(**)+-07365')).toBeGreaterThanOrEqual(comp.measureStrength('Aa090(**)')); + }); + + it('should change the color based on strength', () => { + expect(comp.getColor(0).col).toBe(comp.colors[0]); + expect(comp.getColor(11).col).toBe(comp.colors[1]); + expect(comp.getColor(22).col).toBe(comp.colors[2]); + expect(comp.getColor(33).col).toBe(comp.colors[3]); + expect(comp.getColor(44).col).toBe(comp.colors[4]); + }); + }); +}); diff --git a/src/test/javascript/spec/component/account/password.component.spec.ts b/src/test/javascript/spec/component/account/password.component.spec.ts new file mode 100644 index 000000000000..d4219432a4ee --- /dev/null +++ b/src/test/javascript/spec/component/account/password.component.spec.ts @@ -0,0 +1,86 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { of, throwError } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { PasswordComponent } from 'app/account/password/password.component'; +import { PasswordService } from 'app/account/password/password.service'; + +describe('PasswordComponent', () => { + let comp: PasswordComponent; + let fixture: ComponentFixture; + let service: PasswordService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [PasswordComponent], + }) + .overrideTemplate(PasswordComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(PasswordComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(PasswordService); + }); + + it('should show error if passwords do not match', () => { + // GIVEN + comp.newPassword = 'password1'; + comp.confirmPassword = 'password2'; + // WHEN + comp.changePassword(); + // THEN + expect(comp.doNotMatch).toBe('ERROR'); + expect(comp.error).toBeNull(); + expect(comp.success).toBeNull(); + }); + + it('should call Auth.changePassword when passwords match', () => { + // GIVEN + const passwordValues = { + currentPassword: 'oldPassword', + newPassword: 'myPassword', + }; + + spyOn(service, 'save').and.returnValue(of(new HttpResponse({ body: true }))); + comp.currentPassword = passwordValues.currentPassword; + comp.newPassword = comp.confirmPassword = passwordValues.newPassword; + + // WHEN + comp.changePassword(); + + // THEN + expect(service.save).toHaveBeenCalledWith(passwordValues.newPassword, passwordValues.currentPassword); + }); + + it('should set success to OK upon success', function () { + // GIVEN + spyOn(service, 'save').and.returnValue(of(new HttpResponse({ body: true }))); + comp.newPassword = comp.confirmPassword = 'myPassword'; + + // WHEN + comp.changePassword(); + + // THEN + expect(comp.doNotMatch).toBeNull(); + expect(comp.error).toBeNull(); + expect(comp.success).toBe('OK'); + }); + + it('should notify of error if change password fails', function () { + // GIVEN + spyOn(service, 'save').and.returnValue(throwError('ERROR')); + comp.newPassword = comp.confirmPassword = 'myPassword'; + + // WHEN + comp.changePassword(); + + // THEN + expect(comp.doNotMatch).toBeNull(); + expect(comp.success).toBeNull(); + expect(comp.error).toBe('ERROR'); + }); +}); diff --git a/src/test/javascript/spec/component/account/register.component.spec.ts b/src/test/javascript/spec/component/account/register.component.spec.ts new file mode 100644 index 000000000000..59866dfbffc9 --- /dev/null +++ b/src/test/javascript/spec/component/account/register.component.spec.ts @@ -0,0 +1,121 @@ +import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; +import { of, throwError } from 'rxjs'; + +import { JhiLanguageService } from 'ng-jhipster'; +import { MockLanguageService } from '../../helpers/mocks/service/mock-language.service'; +import { ArtemisTestModule } from '../../test.module'; +import { EMAIL_ALREADY_USED_TYPE, LOGIN_ALREADY_USED_TYPE } from 'app/shared/constants/error.constants'; +import { RegisterService } from 'app/account/register/register.service'; +import { RegisterComponent } from 'app/account/register/register.component'; + +describe('RegisterComponent', () => { + let fixture: ComponentFixture; + let comp: RegisterComponent; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [RegisterComponent], + }) + .overrideTemplate(RegisterComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(RegisterComponent); + comp = fixture.componentInstance; + comp.ngOnInit(); + }); + + it('should ensure the two passwords entered match', () => { + comp.registerAccount.password = 'password'; + comp.confirmPassword = 'non-matching'; + + comp.register(); + + expect(comp.doNotMatch).toEqual('ERROR'); + }); + + it('should update success to OK after creating an account', inject( + [RegisterService, JhiLanguageService], + fakeAsync((service: RegisterService, mockTranslate: MockLanguageService) => { + spyOn(service, 'save').and.returnValue(of({})); + comp.registerAccount.password = comp.confirmPassword = 'password'; + + comp.register(); + tick(); + + expect(service.save).toHaveBeenCalledWith( + expect.objectContaining({ + password: 'password', + langKey: 'en', + }), + ); + expect(comp.success).toEqual(true); + expect(comp.registerAccount.langKey).toEqual('en'); + expect(mockTranslate.getCurrentSpy).toHaveBeenCalled(); + expect(comp.errorUserExists).toBeNull(); + expect(comp.errorEmailExists).toBeNull(); + expect(comp.error).toBeNull(); + }), + )); + + it('should notify of user existence upon 400/login already in use', inject( + [RegisterService], + fakeAsync((service: RegisterService) => { + spyOn(service, 'save').and.returnValue( + throwError({ + status: 400, + error: { type: LOGIN_ALREADY_USED_TYPE }, + }), + ); + comp.registerAccount.password = comp.confirmPassword = 'password'; + + comp.register(); + tick(); + + expect(comp.errorUserExists).toEqual('ERROR'); + expect(comp.errorEmailExists).toBeNull(); + expect(comp.error).toBeNull(); + }), + )); + + it('should notify of email existence upon 400/email address already in use', inject( + [RegisterService], + fakeAsync((service: RegisterService) => { + spyOn(service, 'save').and.returnValue( + throwError({ + status: 400, + error: { type: EMAIL_ALREADY_USED_TYPE }, + }), + ); + comp.registerAccount.password = comp.confirmPassword = 'password'; + + comp.register(); + tick(); + + expect(comp.errorEmailExists).toEqual('ERROR'); + expect(comp.errorUserExists).toBeNull(); + expect(comp.error).toBeNull(); + }), + )); + + it('should notify of generic error', inject( + [RegisterService], + fakeAsync((service: RegisterService) => { + spyOn(service, 'save').and.returnValue( + throwError({ + status: 503, + }), + ); + comp.registerAccount.password = comp.confirmPassword = 'password'; + + comp.register(); + tick(); + + expect(comp.errorUserExists).toBeNull(); + expect(comp.errorEmailExists).toBeNull(); + expect(comp.error).toEqual('ERROR'); + }), + )); +}); diff --git a/src/test/javascript/spec/component/account/settings.component.spec.ts b/src/test/javascript/spec/component/account/settings.component.spec.ts new file mode 100644 index 000000000000..9a0ad8c9fd78 --- /dev/null +++ b/src/test/javascript/spec/component/account/settings.component.spec.ts @@ -0,0 +1,58 @@ +import { ComponentFixture, TestBed, async } from '@angular/core/testing'; +import { FormBuilder } from '@angular/forms'; +import { throwError, of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { AccountService } from 'app/core/auth/account.service'; +import { Account } from 'app/core/user/account.model'; +import { SettingsComponent } from 'app/account/settings/settings.component'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; + +describe('SettingsComponent', () => { + let comp: SettingsComponent; + let fixture: ComponentFixture; + let accountService: AccountService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [SettingsComponent], + providers: [FormBuilder, { provide: AccountService, useClass: MockAccountService }], + }) + .overrideTemplate(SettingsComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(SettingsComponent); + comp = fixture.componentInstance; + accountService = TestBed.get(AccountService); + comp.settingsAccount = { langKey: 'en' } as Account; + }); + + it('should notify of success upon successful save', () => { + // GIVEN + spyOn(accountService, 'save').and.returnValue(of({})); + + // WHEN + comp.ngOnInit(); + comp.save(); + + // THEN + expect(comp.success).toBe('OK'); + expect(comp.error).toBe(null); + }); + + it('should notify of error upon failed save', () => { + // GIVEN + spyOn(accountService, 'save').and.returnValue(throwError('An error message')); + + // WHEN + comp.ngOnInit(); + comp.save(); + + // THEN + expect(comp.success).toBe(null); + expect(comp.error).toBe('ERROR'); + }); +}); diff --git a/src/test/javascript/spec/component/admin/audits.component.spec.ts b/src/test/javascript/spec/component/admin/audits.component.spec.ts new file mode 100644 index 000000000000..321c0508090a --- /dev/null +++ b/src/test/javascript/spec/component/admin/audits.component.spec.ts @@ -0,0 +1,101 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { ArtemisTestModule } from '../../test.module'; +import { AuditsComponent } from 'app/admin/audits/audits.component'; +import { AuditsService } from 'app/admin/audits/audits.service'; +import { Audit } from 'app/admin/audits/audit.model'; +import { ITEMS_PER_PAGE } from 'app/shared/constants/pagination.constants'; + +function build2DigitsDatePart(datePart: number) { + return `0${datePart}`.slice(-2); +} + +function getDate(isToday = true) { + let date: Date = new Date(); + if (isToday) { + // Today + 1 day - needed if the current day must be included + date.setDate(date.getDate() + 1); + } else { + // get last month + if (date.getMonth() === 0) { + date = new Date(date.getFullYear() - 1, 11, date.getDate()); + } else { + date = new Date(date.getFullYear(), date.getMonth() - 1, date.getDate()); + } + } + const monthString = build2DigitsDatePart(date.getMonth() + 1); + const dateString = build2DigitsDatePart(date.getDate()); + return `${date.getFullYear()}-${monthString}-${dateString}`; +} + +describe('AuditsComponent', () => { + let comp: AuditsComponent; + let fixture: ComponentFixture; + let service: AuditsService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [AuditsComponent], + providers: [AuditsService], + }) + .overrideTemplate(AuditsComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(AuditsComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(AuditsService); + }); + + describe('today function ', () => { + it('should set toDate to current date', () => { + comp.today(); + expect(comp.toDate).toBe(getDate()); + }); + }); + + describe('previousMonth function ', () => { + it('should set fromDate to current date', () => { + comp.previousMonth(); + expect(comp.fromDate).toBe(getDate(false)); + }); + }); + + describe('By default, on init', () => { + it('should set all default values correctly', () => { + fixture.detectChanges(); + expect(comp.toDate).toBe(getDate()); + expect(comp.fromDate).toBe(getDate(false)); + expect(comp.itemsPerPage).toBe(ITEMS_PER_PAGE); + expect(comp.page).toBe(1); + expect(comp.reverse).toBeFalsy(); + }); + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + const audit = new Audit({ remoteAddress: '127.0.0.1', sessionId: '123' }, 'user', '20140101', 'AUTHENTICATION_SUCCESS'); + spyOn(service, 'query').and.returnValue( + of( + new HttpResponse({ + body: [audit], + headers, + }), + ), + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.query).toHaveBeenCalled(); + expect(comp.audits[0]).toEqual(jasmine.objectContaining(audit)); + }); + }); +}); diff --git a/src/test/javascript/spec/component/admin/configuration.component.spec.ts b/src/test/javascript/spec/component/admin/configuration.component.spec.ts new file mode 100644 index 000000000000..e9cbb05ddf33 --- /dev/null +++ b/src/test/javascript/spec/component/admin/configuration.component.spec.ts @@ -0,0 +1,66 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { JhiConfigurationComponent } from 'app/admin/configuration/configuration.component'; +import { JhiConfigurationService } from 'app/admin/configuration/configuration.service'; + +describe('JhiConfigurationComponent', () => { + let comp: JhiConfigurationComponent; + let fixture: ComponentFixture; + let service: JhiConfigurationService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [JhiConfigurationComponent], + providers: [JhiConfigurationService], + }) + .overrideTemplate(JhiConfigurationComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(JhiConfigurationComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JhiConfigurationService); + }); + + describe('OnInit', () => { + it('should set all default values correctly', () => { + expect(comp.configKeys).toEqual([]); + expect(comp.filter).toBe(''); + expect(comp.orderProp).toBe('prefix'); + expect(comp.reverse).toBe(false); + }); + it('Should call load all on init', () => { + // GIVEN + const body = [{ config: 'test', properties: 'test' }, { config: 'test2' }]; + const envConfig = { envConfig: 'test' }; + spyOn(service, 'get').and.returnValue(of(body)); + spyOn(service, 'getEnv').and.returnValue(of(envConfig)); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.get).toHaveBeenCalled(); + expect(service.getEnv).toHaveBeenCalled(); + expect(comp.configKeys).toEqual([['0', '1', '2', '3']]); + expect(comp.allConfiguration).toEqual(envConfig); + }); + }); + describe('keys method', () => { + it('should return the keys of an Object', () => { + // GIVEN + const data = { + key1: 'test', + key2: 'test2', + }; + + // THEN + expect(comp.keys(data)).toEqual(['key1', 'key2']); + expect(comp.keys(undefined)).toEqual([]); + }); + }); +}); diff --git a/src/test/javascript/spec/component/admin/health.component.spec.ts b/src/test/javascript/spec/component/admin/health.component.spec.ts new file mode 100644 index 000000000000..841c8c164dda --- /dev/null +++ b/src/test/javascript/spec/component/admin/health.component.spec.ts @@ -0,0 +1,65 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpErrorResponse } from '@angular/common/http'; +import { of, throwError } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { HealthComponent } from 'app/admin/health/health.component'; +import { Health, HealthService } from 'app/admin/health/health.service'; + +describe('HealthComponent', () => { + let comp: HealthComponent; + let fixture: ComponentFixture; + let service: HealthService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [HealthComponent], + }) + .overrideTemplate(HealthComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(HealthComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(HealthService); + }); + + describe('getBadgeClass', () => { + it('should get badge class', () => { + const upBadgeClass = comp.getBadgeClass('UP'); + const downBadgeClass = comp.getBadgeClass('DOWN'); + expect(upBadgeClass).toEqual('badge-success'); + expect(downBadgeClass).toEqual('badge-danger'); + }); + }); + + describe('refresh', () => { + it('should call refresh on init', () => { + // GIVEN + const health: Health = { status: 'UP', components: { mail: { status: 'UP', details: 'mailDetails' } } }; + spyOn(service, 'checkHealth').and.returnValue(of(health)); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.checkHealth).toHaveBeenCalled(); + expect(comp.health).toEqual(health); + }); + + it('should handle a 503 on refreshing health data', () => { + // GIVEN + const health: Health = { status: 'DOWN', components: { mail: { status: 'DOWN', details: 'mailDetails' } } }; + spyOn(service, 'checkHealth').and.returnValue(throwError(new HttpErrorResponse({ status: 503, error: health }))); + + // WHEN + comp.refresh(); + + // THEN + expect(service.checkHealth).toHaveBeenCalled(); + expect(comp.health).toEqual(health); + }); + }); +}); diff --git a/src/test/javascript/spec/component/admin/logs.component.spec.ts b/src/test/javascript/spec/component/admin/logs.component.spec.ts new file mode 100644 index 000000000000..5c525e762ed2 --- /dev/null +++ b/src/test/javascript/spec/component/admin/logs.component.spec.ts @@ -0,0 +1,74 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; + +import { ArtemisTestModule } from '../../test.module'; +import { LogsComponent } from 'app/admin/logs/logs.component'; +import { LogsService } from 'app/admin/logs/logs.service'; +import { Log } from 'app/admin/logs/log.model'; + +describe('LogsComponent', () => { + let comp: LogsComponent; + let fixture: ComponentFixture; + let service: LogsService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [LogsComponent], + providers: [LogsService], + }) + .overrideTemplate(LogsComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(LogsComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(LogsService); + }); + + describe('OnInit', () => { + it('should set all default values correctly', () => { + expect(comp.filter).toBe(''); + expect(comp.orderProp).toBe('name'); + expect(comp.reverse).toBe(false); + }); + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + const log = new Log('main', 'WARN'); + spyOn(service, 'findAll').and.returnValue( + of( + new HttpResponse({ + body: [log], + headers, + }), + ), + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.findAll).toHaveBeenCalled(); + expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log)); + }); + }); + describe('change log level', () => { + it('should change log level correctly', () => { + // GIVEN + const log = new Log('main', 'ERROR'); + spyOn(service, 'changeLevel').and.returnValue(of(new HttpResponse())); + spyOn(service, 'findAll').and.returnValue(of(new HttpResponse({ body: [log] }))); + + // WHEN + comp.changeLevel('main', 'ERROR'); + + // THEN + expect(service.changeLevel).toHaveBeenCalled(); + expect(service.findAll).toHaveBeenCalled(); + expect(comp.loggers[0]).toEqual(jasmine.objectContaining(log)); + }); + }); +}); diff --git a/src/test/javascript/spec/component/admin/metrics.component.spec.ts b/src/test/javascript/spec/component/admin/metrics.component.spec.ts new file mode 100644 index 000000000000..daa0acc85f0f --- /dev/null +++ b/src/test/javascript/spec/component/admin/metrics.component.spec.ts @@ -0,0 +1,52 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { JhiMetricsMonitoringComponent } from 'app/admin/metrics/metrics.component'; +import { JhiMetricsService } from 'app/admin/metrics/metrics.service'; + +describe('JhiMetricsMonitoringComponent', () => { + let comp: JhiMetricsMonitoringComponent; + let fixture: ComponentFixture; + let service: JhiMetricsService; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [JhiMetricsMonitoringComponent], + }) + .overrideTemplate(JhiMetricsMonitoringComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(JhiMetricsMonitoringComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(JhiMetricsService); + }); + + describe('refresh', () => { + it('should call refresh on init', () => { + // GIVEN + const response = { + timers: { + service: 'test', + unrelatedKey: 'test', + }, + gauges: { + 'jcache.statistics': { + value: 2, + }, + unrelatedKey: 'test', + }, + }; + spyOn(service, 'getMetrics').and.returnValue(of(response)); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.getMetrics).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/test/javascript/spec/component/admin/user-management-detail.component.spec.ts b/src/test/javascript/spec/component/admin/user-management-detail.component.spec.ts new file mode 100644 index 000000000000..a1a08af7fec9 --- /dev/null +++ b/src/test/javascript/spec/component/admin/user-management-detail.component.spec.ts @@ -0,0 +1,67 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { UserManagementDetailComponent } from 'app/admin/user-management/user-management-detail.component'; +import { User } from 'app/core/user/user.model'; + +describe('User Management Detail Component', () => { + let comp: UserManagementDetailComponent; + let fixture: ComponentFixture; + const route = ({ + data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', ['ROLE_USER'], 'admin', null, null, null) }), + } as any) as ActivatedRoute; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [UserManagementDetailComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: route, + }, + ], + }) + .overrideTemplate(UserManagementDetailComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(UserManagementDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.user).toEqual( + jasmine.objectContaining({ + id: 1, + login: 'user', + firstName: 'first', + lastName: 'last', + email: 'first@last.com', + activated: true, + langKey: 'en', + authorities: ['ROLE_USER'], + createdBy: null, + createdDate: null, + lastModifiedBy: null, + lastModifiedDate: null, + password: null, + groups: 'admin', + guidedTourSettings: [], + imageUrl: null, + lastNotificationRead: null, + }), + ); + }); + }); +}); diff --git a/src/test/javascript/spec/component/admin/user-management-update.component.spec.ts b/src/test/javascript/spec/component/admin/user-management-update.component.spec.ts new file mode 100644 index 000000000000..8255a43c7e53 --- /dev/null +++ b/src/test/javascript/spec/component/admin/user-management-update.component.spec.ts @@ -0,0 +1,102 @@ +import { async, ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { UserManagementUpdateComponent } from 'app/admin/user-management/user-management-update.component'; +import { User } from 'app/core/user/user.model'; +import { JhiLanguageHelper } from 'app/core/language/language.helper'; +import { UserService } from 'app/core/user/user.service'; + +describe('User Management Update Component', () => { + let comp: UserManagementUpdateComponent; + let fixture: ComponentFixture; + let service: UserService; + let mockLanguageHelper: any; + const route = ({ + data: of({ user: new User(1, 'user', 'first', 'last', 'first@last.com', true, 'en', ['ROLE_USER'], 'admin', null, null, null) }), + } as any) as ActivatedRoute; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [UserManagementUpdateComponent], + providers: [ + { + provide: ActivatedRoute, + useValue: route, + }, + ], + }) + .overrideTemplate(UserManagementUpdateComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(UserManagementUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(UserService); + mockLanguageHelper = fixture.debugElement.injector.get(JhiLanguageHelper); + }); + + describe('OnInit', () => { + it('Should load authorities and language on init', inject( + [], + fakeAsync(() => { + // GIVEN + spyOn(service, 'authorities').and.returnValue(of(['USER'])); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.authorities).toHaveBeenCalled(); + expect(comp.authorities).toEqual(['USER']); + expect(mockLanguageHelper.getAllSpy).toHaveBeenCalled(); + }), + )); + }); + + describe('save', () => { + it('Should call update service on save for existing user', inject( + [], + fakeAsync(() => { + // GIVEN + const entity = new User(123); + spyOn(service, 'update').and.returnValue( + of( + new HttpResponse({ + body: entity, + }), + ), + ); + comp.user = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + }), + )); + + it('Should call create service on save for new user', inject( + [], + fakeAsync(() => { + // GIVEN + const entity = new User(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.user = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + }), + )); + }); +}); diff --git a/src/test/javascript/spec/component/admin/user-management.spec.ts b/src/test/javascript/spec/component/admin/user-management.component.spec.ts similarity index 82% rename from src/test/javascript/spec/component/admin/user-management.spec.ts rename to src/test/javascript/spec/component/admin/user-management.component.spec.ts index 5d5c0e596534..fdfb732b0f26 100644 --- a/src/test/javascript/spec/component/admin/user-management.spec.ts +++ b/src/test/javascript/spec/component/admin/user-management.component.spec.ts @@ -1,16 +1,14 @@ -/* tslint:disable:no-unused-expression */ import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { TranslateModule } from '@ngx-translate/core'; -import { DebugElement } from '@angular/core'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisAdminModule } from 'app/admin/admin.module'; import { UserManagementComponent } from 'app/admin/user-management/user-management.component'; import { UserService } from 'app/core/user/user.service'; -import { MockUserService } from '../../mocks/mock-user.service'; +import { MockUserService } from '../../helpers/mocks/service/mock-user.service'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; chai.use(sinonChai); const expect = chai.expect; @@ -18,7 +16,6 @@ const expect = chai.expect; describe('UserManagementComponent', () => { let comp: UserManagementComponent; let fixture: ComponentFixture; - let debugElement: DebugElement; beforeEach(async () => { return TestBed.configureTestingModule({ @@ -32,11 +29,11 @@ describe('UserManagementComponent', () => { .then(() => { fixture = TestBed.createComponent(UserManagementComponent); comp = fixture.componentInstance; - debugElement = fixture.debugElement; }); }); - // The admin module is lazy loaded - we therefore need a dummy test to load the module and verify that there are no dependency related issues. + // The admin module is lazy loaded - we therefore need a dummy test to load + // the module and verify that there are no dependency related issues. it('should render a component from the admin module', () => { expect(comp).to.exist; }); diff --git a/src/test/javascript/spec/component/assessment-shared/assessment-layout.component.spec.ts b/src/test/javascript/spec/component/assessment-shared/assessment-layout.component.spec.ts index dd6fba64619e..8d6f60b381ec 100644 --- a/src/test/javascript/spec/component/assessment-shared/assessment-layout.component.spec.ts +++ b/src/test/javascript/spec/component/assessment-shared/assessment-layout.component.spec.ts @@ -1,7 +1,6 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { TranslateModule } from '@ngx-translate/core'; -import { AlertService } from 'app/core/alert/alert.service'; import { ArtemisTestModule } from '../../test.module'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; diff --git a/src/test/javascript/spec/component/admin/admin.spec.ts b/src/test/javascript/spec/component/audits/audits.component.spec.ts similarity index 78% rename from src/test/javascript/spec/component/admin/admin.spec.ts rename to src/test/javascript/spec/component/audits/audits.component.spec.ts index 07669ec72663..56c22e88c1b0 100644 --- a/src/test/javascript/spec/component/admin/admin.spec.ts +++ b/src/test/javascript/spec/component/audits/audits.component.spec.ts @@ -1,7 +1,5 @@ -/* tslint:disable:no-unused-expression */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TranslateModule } from '@ngx-translate/core'; -import { DebugElement } from '@angular/core'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; @@ -11,10 +9,9 @@ import { AuditsComponent } from 'app/admin/audits/audits.component'; chai.use(sinonChai); const expect = chai.expect; -describe('AdminModule', () => { +describe('AuditsComponent', () => { let comp: AuditsComponent; let fixture: ComponentFixture; - let debugElement: DebugElement; beforeEach(async () => { return TestBed.configureTestingModule({ @@ -24,11 +21,11 @@ describe('AdminModule', () => { .then(() => { fixture = TestBed.createComponent(AuditsComponent); comp = fixture.componentInstance; - debugElement = fixture.debugElement; }); }); - // The admin module is lazy loaded - we therefore need a dummy test to load the module and verify that there are no dependency related issues. + // The admin module is lazy loaded - we therefore need a dummy test to load + // the module and verify that there are no dependency related issues. it('should render a component from the admin module', () => { expect(comp).to.exist; }); diff --git a/src/test/javascript/spec/component/code-editor/code-editor-ace.spec.ts b/src/test/javascript/spec/component/code-editor/code-editor-ace.component.spec.ts similarity index 98% rename from src/test/javascript/spec/component/code-editor/code-editor-ace.spec.ts rename to src/test/javascript/spec/component/code-editor/code-editor-ace.component.spec.ts index d11f6b5e8731..0693f29678d5 100644 --- a/src/test/javascript/spec/component/code-editor/code-editor-ace.spec.ts +++ b/src/test/javascript/spec/component/code-editor/code-editor-ace.component.spec.ts @@ -11,12 +11,12 @@ import { SinonStub, spy, stub } from 'sinon'; import { Subject } from 'rxjs'; import { ArtemisTestModule } from '../../test.module'; import { CreateFileChange, FileType, RenameFileChange } from 'app/exercises/programming/shared/code-editor/model/code-editor.model'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { AnnotationArray } from 'app/entities/annotation.model'; import { CodeEditorRepositoryFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service'; import { CodeEditorFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-file.service'; import { CodeEditorAceComponent } from 'app/exercises/programming/shared/code-editor/ace/code-editor-ace.component'; -import { MockCodeEditorRepositoryFileService } from '../../mocks/mock-code-editor-repository-file.service'; +import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/component/code-editor/code-editor-actions.spec.ts b/src/test/javascript/spec/component/code-editor/code-editor-actions.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/code-editor/code-editor-actions.spec.ts rename to src/test/javascript/spec/component/code-editor/code-editor-actions.component.spec.ts index 6d2b0b51f973..282153f8da27 100644 --- a/src/test/javascript/spec/component/code-editor/code-editor-actions.spec.ts +++ b/src/test/javascript/spec/component/code-editor/code-editor-actions.component.spec.ts @@ -15,16 +15,16 @@ import { CodeEditorRepositoryFileService, CodeEditorRepositoryService } from 'ap import { ArtemisTestModule } from '../../test.module'; import { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module'; import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; -import { MockFeatureToggleService } from '../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service'; import { cartesianProduct } from 'app/shared/util/utils'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { CodeEditorConflictStateService } from 'app/exercises/programming/shared/code-editor/service/code-editor-conflict-state.service'; import { CodeEditorActionsComponent } from 'app/exercises/programming/shared/code-editor/actions/code-editor-actions.component'; -import { MockCodeEditorConflictStateService } from '../../mocks/mock-code-editor-conflict-state.service'; -import { MockCodeEditorRepositoryFileService } from '../../mocks/mock-code-editor-repository-file.service'; -import { MockCodeEditorRepositoryService } from '../../mocks/mock-code-editor-repository.service'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockCodeEditorConflictStateService } from '../../helpers/mocks/service/mock-code-editor-conflict-state.service'; +import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service'; +import { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { CommitState, EditorState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model'; chai.use(sinonChai); diff --git a/src/test/javascript/spec/component/code-editor/code-editor-build-output.spec.ts b/src/test/javascript/spec/component/code-editor/code-editor-build-output.component.spec.ts similarity index 92% rename from src/test/javascript/spec/component/code-editor/code-editor-build-output.spec.ts rename to src/test/javascript/spec/component/code-editor/code-editor-build-output.component.spec.ts index 2a6918093403..7a1e39182946 100644 --- a/src/test/javascript/spec/component/code-editor/code-editor-build-output.spec.ts +++ b/src/test/javascript/spec/component/code-editor/code-editor-build-output.component.spec.ts @@ -11,7 +11,7 @@ import { SinonStub, stub } from 'sinon'; import { Observable, of } from 'rxjs'; import { ArtemisTestModule } from '../../test.module'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { CodeEditorBuildOutputComponent } from 'app/exercises/programming/shared/code-editor/build-output/code-editor-build-output.component'; import { Participation } from 'app/entities/participation/participation.model'; import { BuildLogEntryArray } from 'app/entities/build-log.model'; @@ -21,12 +21,12 @@ import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ResultService } from 'app/exercises/shared/result/result.service'; import { AnnotationArray } from 'app/entities/annotation.model'; import { Feedback } from 'app/entities/feedback.model'; -import { MockResultService } from '../../mocks/mock-result.service'; -import { MockCodeEditorBuildLogService } from '../../mocks/mock-code-editor-build-log.service'; -import { MockCodeEditorSessionService } from '../../mocks/mock-code-editor-session.service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockResultService } from '../../helpers/mocks/service/mock-result.service'; +import { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service'; +import { MockCodeEditorSessionService } from '../../helpers/mocks/service/mock-code-editor-session.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; chai.use(sinonChai); const expect = chai.expect; @@ -93,7 +93,8 @@ describe('CodeEditorBuildOutputComponent', () => { { time: '2019-05-15T10:32:11+02:00', log: - '[ERROR] /var/atlassian/application-data/bamboo/xml-data/build-dir/COURSEPROGSHORT-BASE-JOB1/assignment/src/todo/main/BubbleSort.java:[8,12] cannot find symbol', + '[ERROR] /var/atlassian/application-data/bamboo/xml-data/build-dir/COURSEPROGSHORT-BASE-JOB1' + + '/assignment/src/todo/main/BubbleSort.java:[8,12] cannot find symbol', }, { time: '2019-05-15T10:32:11+02:00', @@ -196,7 +197,8 @@ describe('CodeEditorBuildOutputComponent', () => { { time: '2019-05-15T10:32:11+02:00', log: - '[ERROR] /var/atlassian/application-data/bamboo/xml-data/build-dir/COURSEPROGSHORT-BASE-JOB1/assignment/src/todo/main/BubbleSort.java:[8,12] cannot find symbol', + '[ERROR] /var/atlassian/application-data/bamboo/xml-data/build-dir/COURSEPROGSHORT-BASE-JOB1/' + + 'assignment/src/todo/main/BubbleSort.java:[8,12] cannot find symbol', }, { time: '2019-05-15T10:32:11+02:00', diff --git a/src/test/javascript/spec/component/code-editor/code-editor-file-browser.spec.ts b/src/test/javascript/spec/component/code-editor/code-editor-file-browser.component.spec.ts similarity index 92% rename from src/test/javascript/spec/component/code-editor/code-editor-file-browser.spec.ts rename to src/test/javascript/spec/component/code-editor/code-editor-file-browser.component.spec.ts index 9df585545167..5fb7a0e6fcf2 100644 --- a/src/test/javascript/spec/component/code-editor/code-editor-file-browser.spec.ts +++ b/src/test/javascript/spec/component/code-editor/code-editor-file-browser.component.spec.ts @@ -14,7 +14,7 @@ import { SinonStub, spy, stub } from 'sinon'; import { Observable, Subject } from 'rxjs'; import { ArtemisTestModule } from '../../test.module'; import { CommitState, FileType, GitConflictState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { DeviceDetectorService } from 'ngx-device-detector'; import { CodeEditorRepositoryFileService, CodeEditorRepositoryService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service'; import { CodeEditorConflictStateService } from 'app/exercises/programming/shared/code-editor/service/code-editor-conflict-state.service'; @@ -24,11 +24,11 @@ import { CodeEditorFileBrowserCreateNodeComponent } from 'app/exercises/programm import { CodeEditorFileBrowserFileComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser-file.component'; import { CodeEditorFileBrowserComponent } from 'app/exercises/programming/shared/code-editor/file-browser/code-editor-file-browser.component'; import { CodeEditorStatusComponent } from 'app/exercises/programming/shared/code-editor/status/code-editor-status.component'; -import { MockCodeEditorRepositoryService } from '../../mocks/mock-code-editor-repository.service'; -import { MockCodeEditorRepositoryFileService } from '../../mocks/mock-code-editor-repository-file.service'; -import { MockCodeEditorConflictStateService } from '../../mocks/mock-code-editor-conflict-state.service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service'; +import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service'; +import { MockCodeEditorConflictStateService } from '../../helpers/mocks/service/mock-code-editor-conflict-state.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; chai.use(sinonChai); const expect = chai.expect; @@ -139,56 +139,6 @@ describe('CodeEditorFileBrowserComponent', () => { 'folder2/folder3': FileType.FOLDER, 'folder2/folder3/file3': FileType.FILE, }; - const expectedTreeviewItems = [ - new TreeviewItem({ - internalDisabled: false, - internalChecked: false, - internalCollapsed: false, - text: 'folder', - value: 'folder', - internalChildren: [ - new TreeviewItem({ - internalDisabled: false, - internalChecked: false, - internalCollapsed: false, - text: 'file1', - value: 'folder/file1', - } as any), - ], - } as any), - new TreeviewItem({ - internalDisabled: false, - internalChecked: false, - internalCollapsed: false, - text: 'folder2', - value: 'folder2', - internalChildren: [ - new TreeviewItem({ - internalDisabled: false, - internalChecked: false, - internalCollapsed: false, - text: 'file2', - value: 'folder2/file2', - } as any), - new TreeviewItem({ - internalDisabled: false, - internalChecked: false, - internalCollapsed: false, - text: 'folder3', - value: 'folder2/folder3', - internalChildren: [ - new TreeviewItem({ - internalDisabled: false, - internalChecked: false, - internalCollapsed: false, - text: 'file3', - value: 'folder2/file3', - } as any), - ], - } as any), - ], - } as any), - ]; comp.repositoryFiles = repositoryFiles; comp.setupTreeview(); fixture.detectChanges(); @@ -311,7 +261,7 @@ describe('CodeEditorFileBrowserComponent', () => { folder2: FileType.FOLDER, 'folder/file2': FileType.FILE, }; - const treeItems = [ + comp.filesTreeViewItem = [ new TreeviewItem({ internalDisabled: false, internalChecked: false, @@ -327,7 +277,6 @@ describe('CodeEditorFileBrowserComponent', () => { value: 'file2', } as any), ]; - comp.filesTreeViewItem = treeItems; comp.repositoryFiles = repositoryFiles; comp.selectedFile = selectedFile; triggerChanges(comp, { property: 'selectedFile', currentValue: 'folder/file2', firstChange: false }); @@ -349,7 +298,7 @@ describe('CodeEditorFileBrowserComponent', () => { expect(areUnSelected).to.be.true; }); - it('should add file to node tree if created', fakeAsync((done: any) => { + it('should add file to node tree if created', fakeAsync(() => { const fileName = 'file2'; const filePath = 'folder2/file2'; const repositoryFiles = { file1: FileType.FILE, folder2: FileType.FOLDER }; diff --git a/src/test/javascript/spec/component/code-editor/code-editor-instructions.spec.ts b/src/test/javascript/spec/component/code-editor/code-editor-instructions.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/code-editor/code-editor-instructions.spec.ts rename to src/test/javascript/spec/component/code-editor/code-editor-instructions.component.spec.ts index b15b91f93530..e0d1df646feb 100644 --- a/src/test/javascript/spec/component/code-editor/code-editor-instructions.spec.ts +++ b/src/test/javascript/spec/component/code-editor/code-editor-instructions.component.spec.ts @@ -9,7 +9,7 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { AceEditorModule } from 'ng2-ace-editor'; import { ArtemisTestModule } from '../../test.module'; -import { MockCodeEditorGridService } from '../../mocks/mock-code-editor-grid.service'; +import { MockCodeEditorGridService } from '../../helpers/mocks/service/mock-code-editor-grid.service'; import { CodeEditorRepositoryFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-repository.service'; import { CodeEditorGridService } from 'app/exercises/programming/shared/code-editor/service/code-editor-grid.service'; import { CodeEditorInstructionsComponent } from 'app/exercises/programming/shared/code-editor/instructions/code-editor-instructions.component'; @@ -17,7 +17,7 @@ import { ProgrammingExerciseInstructionComponent } from 'app/exercises/programmi import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { ProgrammingExerciseEditableInstructionComponent } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-editable-instruction.component'; import { ArtemisMarkdownEditorModule } from 'app/shared/markdown-editor/markdown-editor.module'; -import { MockCodeEditorRepositoryFileService } from '../../mocks/mock-code-editor-repository-file.service'; +import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/component/code-editor/code-editor-status.spec.ts b/src/test/javascript/spec/component/code-editor/code-editor-status.component.spec.ts similarity index 71% rename from src/test/javascript/spec/component/code-editor/code-editor-status.spec.ts rename to src/test/javascript/spec/component/code-editor/code-editor-status.component.spec.ts index 8aad06aebc72..2cc6f41d29b5 100644 --- a/src/test/javascript/spec/component/code-editor/code-editor-status.spec.ts +++ b/src/test/javascript/spec/component/code-editor/code-editor-status.component.spec.ts @@ -1,3 +1,4 @@ +import { DebugElement } from '@angular/core/'; import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { AceEditorModule } from 'ng2-ace-editor'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; @@ -30,34 +31,36 @@ describe('CodeEditorStatusComponent', () => { const editorStateSegment = fixture.debugElement.query(By.css('#editor_state')); expect(editorStateSegment.children).to.be.empty; }); + it('should show an empty status segment for EditorState if no EditorState is given', () => { - const commitStateSegement = fixture.debugElement.query(By.css('#commit_state')); - expect(commitStateSegement.children).to.be.empty; + const commitStateSegment = fixture.debugElement.query(By.css('#commit_state')); + expect(commitStateSegment.children).to.be.empty; }); + Object.keys(EditorState).map((editorState) => it(`should show exactly one status segment for EditorState ${editorState} with an icon and a non empty description`, function () { comp.editorState = editorState as EditorState; fixture.detectChanges(); const editorStateSegment = fixture.debugElement.query(By.css('#editor_state')); - expect(editorStateSegment.children).to.have.length(1); - const icon = editorStateSegment.query(By.css('fa-icon')); - expect(icon).to.exist; - const text = editorStateSegment.query(By.css('span')); - expect(text).to.exist; - expect(text.nativeElement.textContent).not.to.equal(''); + showsExactlyOneStatusSegment(editorStateSegment); }), ); + Object.keys(CommitState).map((commitState) => it(`should show exactly one status segment for CommitState ${commitState} with an icon and a non empty description`, function () { comp.commitState = commitState as CommitState; fixture.detectChanges(); - const commitStateSegement = fixture.debugElement.query(By.css('#commit_state')); - expect(commitStateSegement.children).to.have.length(1); - const icon = commitStateSegement.query(By.css('fa-icon')); - expect(icon).to.exist; - const text = commitStateSegement.query(By.css('span')); - expect(text).to.exist; - expect(text.nativeElement.textContent).not.to.equal(''); + const commitStateSegment = fixture.debugElement.query(By.css('#commit_state')); + showsExactlyOneStatusSegment(commitStateSegment); }), ); + + const showsExactlyOneStatusSegment = (stateSegment: DebugElement) => { + expect(stateSegment.children).to.have.length(1); + const icon = stateSegment.query(By.css('fa-icon')); + expect(icon).to.exist; + const text = stateSegment.query(By.css('span')); + expect(text).to.exist; + expect(text.nativeElement.textContent).not.to.equal(''); + }; }); diff --git a/src/test/javascript/spec/component/complaints-for-tutor/complaints-for-tutor.spec.ts b/src/test/javascript/spec/component/complaints-for-tutor/complaints-for-tutor.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/complaints-for-tutor/complaints-for-tutor.spec.ts rename to src/test/javascript/spec/component/complaints-for-tutor/complaints-for-tutor.component.spec.ts index 3ccbc41af4d3..129b51f1213d 100644 --- a/src/test/javascript/spec/component/complaints-for-tutor/complaints-for-tutor.spec.ts +++ b/src/test/javascript/spec/component/complaints-for-tutor/complaints-for-tutor.component.spec.ts @@ -2,8 +2,8 @@ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import * as chai from 'chai'; import { BrowserModule, By } from '@angular/platform-browser'; import { ComplaintService } from 'app/complaints/complaint.service'; -import { MockComplaintService } from '../../mocks/mock-complaint.service'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { MomentModule } from 'ngx-moment'; diff --git a/src/test/javascript/spec/component/complaints/complaints.spec.ts b/src/test/javascript/spec/component/complaints/complaints.component.spec.ts similarity index 91% rename from src/test/javascript/spec/component/complaints/complaints.spec.ts rename to src/test/javascript/spec/component/complaints/complaints.component.spec.ts index 15e4354438d2..3f444e484d87 100644 --- a/src/test/javascript/spec/component/complaints/complaints.spec.ts +++ b/src/test/javascript/spec/component/complaints/complaints.component.spec.ts @@ -1,14 +1,12 @@ import { async, ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import * as chai from 'chai'; -import { BrowserModule, By } from '@angular/platform-browser'; +import { By } from '@angular/platform-browser'; import { ComplaintService } from 'app/complaints/complaint.service'; -import { MockComplaintResponse, MockComplaintService } from '../../mocks/mock-complaint.service'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockComplaintResponse, MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { MomentModule } from 'ngx-moment'; -import { ClipboardModule } from 'ngx-clipboard'; import { DebugElement } from '@angular/core'; -import { HttpClientModule } from '@angular/common/http'; import { TranslateModule } from '@ngx-translate/core'; import { ComplaintsComponent } from 'app/complaints/complaints.component'; import { ArtemisTestModule } from '../../test.module'; @@ -57,6 +55,7 @@ describe('ComplaintsComponent', () => { expect(textarea.value).to.be.equal(MockComplaintResponse.body.complaintText); expect(textarea.readOnly).to.be.true; })); + it('should show accepted message when complaint is accepted', () => { comp.resultId = 111; comp.ngOnInit(); diff --git a/src/test/javascript/spec/component/course/course-detail.component.spec.ts b/src/test/javascript/spec/component/course/course-detail.component.spec.ts new file mode 100644 index 000000000000..130cb1255324 --- /dev/null +++ b/src/test/javascript/spec/component/course/course-detail.component.spec.ts @@ -0,0 +1,62 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; + +import { ArtemisTestModule } from '../../test.module'; +import { CourseDetailComponent } from 'app/course/manage/course-detail.component'; +import { Course } from 'app/entities/course.model'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; +import { MockCourseManagementService } from '../../helpers/mocks/service/mock-course-management.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; + +describe('Course Management Detail Component', () => { + let comp: CourseDetailComponent; + let fixture: ComponentFixture; + let service: CourseManagementService; + + const course: Course = { id: 123 } as Course; + const route = ({ params: of({ courseId: course.id }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [CourseDetailComponent], + providers: [ + { provide: ActivatedRoute, useValue: route }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: CourseManagementService, useClass: MockCourseManagementService }, + ], + }) + .overrideTemplate(CourseDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(CourseDetailComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CourseManagementService); + }); + + describe('OnInit', () => { + it('Should call load on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'find').and.returnValue( + of( + new HttpResponse({ + body: course, + headers, + }), + ), + ); + + // WHEN + fixture.detectChanges(); + comp.ngOnInit(); + + // THEN + expect(service.find).toHaveBeenCalled(); + expect(comp.course).toEqual(jasmine.objectContaining({ id: course.id })); + }); + }); +}); diff --git a/src/test/javascript/spec/component/course/course-update.component.spec.ts b/src/test/javascript/spec/component/course/course-update.component.spec.ts new file mode 100644 index 000000000000..78ca40f20145 --- /dev/null +++ b/src/test/javascript/spec/component/course/course-update.component.spec.ts @@ -0,0 +1,88 @@ +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import { FormControl, FormGroup } from '@angular/forms'; +import { ArtemisTestModule } from '../../test.module'; +import { CourseUpdateComponent } from 'app/course/manage/course-update.component'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; +import { Course } from 'app/entities/course.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { LocalStorageService } from 'ngx-webstorage'; +import { SessionStorageService } from 'ngx-webstorage'; + +describe('Course Management Update Component', () => { + let comp: CourseUpdateComponent; + let fixture: ComponentFixture; + let service: CourseManagementService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + providers: [ + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + ], + declarations: [CourseUpdateComponent], + }) + .overrideTemplate(CourseUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(CourseUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CourseManagementService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new Course(); + entity.id = 123; + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.course = entity; + comp.courseForm = new FormGroup({ + id: new FormControl(entity.id), + onlineCourse: new FormControl(entity.onlineCourse), + registrationEnabled: new FormControl(entity.registrationEnabled), + presentationScore: new FormControl(entity.presentationScore), + maxComplaints: new FormControl(entity.maxComplaints), + maxComplaintTimeDays: new FormControl(entity.maxComplaintTimeDays), + complaintsEnabled: new FormControl(entity.complaintsEnabled), + studentQuestionsEnabled: new FormControl(entity.studentQuestionsEnabled), + isAtLeastTutor: new FormControl(entity.isAtLeastTutor), + isAtLeastInstructor: new FormControl(entity.isAtLeastInstructor), + }); + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new Course(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.course = entity; + comp.courseForm = new FormGroup({ + onlineCourse: new FormControl(entity.onlineCourse), + registrationEnabled: new FormControl(entity.registrationEnabled), + presentationScore: new FormControl(entity.presentationScore), + maxComplaints: new FormControl(entity.maxComplaints), + maxComplaintTimeDays: new FormControl(entity.maxComplaintTimeDays), + complaintsEnabled: new FormControl(entity.complaintsEnabled), + studentQuestionsEnabled: new FormControl(entity.studentQuestionsEnabled), + isAtLeastTutor: new FormControl(entity.isAtLeastTutor), + isAtLeastInstructor: new FormControl(entity.isAtLeastInstructor), + }); // mocking reactive form + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); +}); diff --git a/src/test/javascript/spec/component/exercise-hint/exercise-hint-detail.component.spec.ts b/src/test/javascript/spec/component/exercise-hint/exercise-hint-detail.component.spec.ts index 0acafe6c6088..fde2e991660c 100644 --- a/src/test/javascript/spec/component/exercise-hint/exercise-hint-detail.component.spec.ts +++ b/src/test/javascript/spec/component/exercise-hint/exercise-hint-detail.component.spec.ts @@ -1,4 +1,3 @@ -/* tslint:disable max-line-length */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { ActivatedRoute } from '@angular/router'; import { of } from 'rxjs'; @@ -7,36 +6,34 @@ import { ExerciseHintDetailComponent } from 'app/exercises/shared/exercise-hint/ import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { ArtemisTestModule } from '../../test.module'; -describe('Component Tests', () => { - describe('ExerciseHint Management Detail Component', () => { - let comp: ExerciseHintDetailComponent; - let fixture: ComponentFixture; - const exerciseHint = new ExerciseHint(); - exerciseHint.id = 123; - const route = ({ data: of({ exerciseHint }), params: of({ exerciseId: 1 }) } as any) as ActivatedRoute; +describe('ExerciseHint Management Detail Component', () => { + let comp: ExerciseHintDetailComponent; + let fixture: ComponentFixture; + const exerciseHint = new ExerciseHint(); + exerciseHint.id = 123; + const route = ({ data: of({ exerciseHint }), params: of({ exerciseId: 1 }) } as any) as ActivatedRoute; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ExerciseHintDetailComponent], - providers: [{ provide: ActivatedRoute, useValue: route }], - }) - .overrideTemplate(ExerciseHintDetailComponent, '') - .compileComponents(); - fixture = TestBed.createComponent(ExerciseHintDetailComponent); - comp = fixture.componentInstance; - }); + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ExerciseHintDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }], + }) + .overrideTemplate(ExerciseHintDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(ExerciseHintDetailComponent); + comp = fixture.componentInstance; + }); - describe('OnInit', () => { - it('Should call load all on init', () => { - // GIVEN + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN - // WHEN - comp.ngOnInit(); + // WHEN + comp.ngOnInit(); - // THEN - expect(comp.exerciseHint).toEqual(jasmine.objectContaining({ id: 123 })); - }); + // THEN + expect(comp.exerciseHint).toEqual(jasmine.objectContaining({ id: 123 })); }); }); }); diff --git a/src/test/javascript/spec/component/exercise-hint/exercise-hint-update.component.spec.ts b/src/test/javascript/spec/component/exercise-hint/exercise-hint-update.component.spec.ts index 739fc921ede2..0d7d3e956ea5 100644 --- a/src/test/javascript/spec/component/exercise-hint/exercise-hint-update.component.spec.ts +++ b/src/test/javascript/spec/component/exercise-hint/exercise-hint-update.component.spec.ts @@ -1,4 +1,3 @@ -/* tslint:disable max-line-length */ import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { HttpResponse } from '@angular/common/http'; import { FormBuilder } from '@angular/forms'; @@ -9,55 +8,53 @@ import { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/e import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { ArtemisTestModule } from '../../test.module'; -describe('Component Tests', () => { - describe('ExerciseHint Management Update Component', () => { - let comp: ExerciseHintUpdateComponent; - let fixture: ComponentFixture; - let service: ExerciseHintService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ExerciseHintUpdateComponent], - providers: [FormBuilder], - }) - .overrideTemplate(ExerciseHintUpdateComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ExerciseHintUpdateComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ExerciseHintService); - }); - - describe('save', () => { - it('Should call update service on save for existing entity', fakeAsync(() => { - // GIVEN - const entity = new ExerciseHint(); - entity.id = 123; - spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.exerciseHint = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.update).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - - it('Should call create service on save for new entity', fakeAsync(() => { - // GIVEN - const entity = new ExerciseHint(); - spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); - comp.exerciseHint = entity; - // WHEN - comp.save(); - tick(); // simulate async - - // THEN - expect(service.create).toHaveBeenCalledWith(entity); - expect(comp.isSaving).toEqual(false); - })); - }); +describe('ExerciseHint Management Update Component', () => { + let comp: ExerciseHintUpdateComponent; + let fixture: ComponentFixture; + let service: ExerciseHintService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ExerciseHintUpdateComponent], + providers: [FormBuilder], + }) + .overrideTemplate(ExerciseHintUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ExerciseHintUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ExerciseHintService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new ExerciseHint(); + entity.id = 123; + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.exerciseHint = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new ExerciseHint(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.exerciseHint = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); }); }); diff --git a/src/test/javascript/spec/component/exercise-hint/exercise-hint.component.spec.ts b/src/test/javascript/spec/component/exercise-hint/exercise-hint.component.spec.ts index fe92550613d1..ae8cf3ae9922 100644 --- a/src/test/javascript/spec/component/exercise-hint/exercise-hint.component.spec.ts +++ b/src/test/javascript/spec/component/exercise-hint/exercise-hint.component.spec.ts @@ -1,4 +1,3 @@ -/* tslint:disable max-line-length */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { of } from 'rxjs'; import { HttpHeaders, HttpResponse } from '@angular/common/http'; @@ -8,47 +7,45 @@ import { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/e import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { ArtemisTestModule } from '../../test.module'; -describe('Component Tests', () => { - describe('ExerciseHint Management Component', () => { - let comp: ExerciseHintComponent; - let fixture: ComponentFixture; - let service: ExerciseHintService; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule], - declarations: [ExerciseHintComponent], - providers: [], - }) - .overrideTemplate(ExerciseHintComponent, '') - .compileComponents(); - - fixture = TestBed.createComponent(ExerciseHintComponent); - comp = fixture.componentInstance; - service = fixture.debugElement.injector.get(ExerciseHintService); - }); - - it('Should call load all on init', () => { - // GIVEN - const headers = new HttpHeaders().append('link', 'link;link'); - const hint = new ExerciseHint(); - hint.id = 123; - - spyOn(service, 'findByExerciseId').and.returnValue( - of( - new HttpResponse({ - body: [hint], - headers, - }), - ), - ); - - // WHEN - comp.ngOnInit(); - - // THEN - expect(service.findByExerciseId).toHaveBeenCalled(); - expect(comp.exerciseHints[0]).toEqual(jasmine.objectContaining({ id: 123 })); - }); +describe('ExerciseHint Management Component', () => { + let comp: ExerciseHintComponent; + let fixture: ComponentFixture; + let service: ExerciseHintService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ExerciseHintComponent], + providers: [], + }) + .overrideTemplate(ExerciseHintComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ExerciseHintComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ExerciseHintService); + }); + + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + const hint = new ExerciseHint(); + hint.id = 123; + + spyOn(service, 'findByExerciseId').and.returnValue( + of( + new HttpResponse({ + body: [hint], + headers, + }), + ), + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(service.findByExerciseId).toHaveBeenCalled(); + expect(comp.exerciseHints[0]).toEqual(jasmine.objectContaining({ id: 123 })); }); }); diff --git a/src/test/javascript/spec/component/exercise-hint/exercise-hint.service.spec.ts b/src/test/javascript/spec/component/exercise-hint/exercise-hint.service.spec.ts deleted file mode 100644 index c45c07584f18..000000000000 --- a/src/test/javascript/spec/component/exercise-hint/exercise-hint.service.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -/* tslint:disable max-line-length */ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { HttpResponse } from '@angular/common/http'; -import * as chai from 'chai'; -import { take } from 'rxjs/operators'; -import { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; -import { ExerciseHint } from 'app/entities/exercise-hint.model'; - -const expect = chai.expect; - -describe('Service Tests', () => { - describe('ExerciseHint Service', () => { - let injector: TestBed; - let service: ExerciseHintService; - let httpMock: HttpTestingController; - let elemDefault: ExerciseHint; - let expectedResult: any; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - expectedResult = {} as HttpResponse; - injector = getTestBed(); - service = injector.get(ExerciseHintService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new ExerciseHint(); - elemDefault.id = 0; - elemDefault.title = 'AAAAAAA'; - elemDefault.content = 'AAAAAAA'; - }); - - describe('Service methods', () => { - it('should find an element', async () => { - const returnedFromService = Object.assign({}, elemDefault); - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(elemDefault); - }); - - it('should create a ExerciseHint', async () => { - const returnedFromService = Object.assign( - { - id: 0, - }, - elemDefault, - ); - const expected = Object.assign({}, returnedFromService); - service - .create(new ExerciseHint()) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should update a ExerciseHint', async () => { - const returnedFromService = Object.assign( - { - title: 'BBBBBB', - content: 'BBBBBB', - }, - elemDefault, - ); - - const expected = Object.assign({}, returnedFromService); - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should delete a ExerciseHint', async () => { - const rxPromise = service.delete(123).subscribe((resp) => (expectedResult = resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - expect(expectedResult).to.be.true; - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/component/file-upload-assessment/file-upload-assessment.spec.ts b/src/test/javascript/spec/component/file-upload-assessment/file-upload-assessment.component.spec.ts similarity index 80% rename from src/test/javascript/spec/component/file-upload-assessment/file-upload-assessment.spec.ts rename to src/test/javascript/spec/component/file-upload-assessment/file-upload-assessment.component.spec.ts index 659697cd01f8..9b739fa79a38 100644 --- a/src/test/javascript/spec/component/file-upload-assessment/file-upload-assessment.spec.ts +++ b/src/test/javascript/spec/component/file-upload-assessment/file-upload-assessment.component.spec.ts @@ -1,4 +1,4 @@ -import { ComponentFixture, fakeAsync, flush, TestBed, tick } from '@angular/core/testing'; +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { AccountService } from 'app/core/auth/account.service'; @@ -7,21 +7,19 @@ import * as sinonChai from 'sinon-chai'; import * as moment from 'moment'; import { SinonStub, stub } from 'sinon'; import { ArtemisTestModule } from '../../test.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { MockComponent } from 'ng-mocks'; import { ArtemisSharedModule } from 'app/shared/shared.module'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { Router } from '@angular/router'; -import { of } from 'rxjs'; import { FileUploadAssessmentComponent } from 'app/exercises/file-upload/assess/file-upload-assessment.component'; import { ResizableInstructionsComponent } from 'app/exercises/text/assess/resizable-instructions/resizable-instructions.component'; import { DebugElement } from '@angular/core'; -import { MockAccountService } from '../../mocks/mock-account.service'; -import { Location } from '@angular/common'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { ComplaintService } from 'app/complaints/complaint.service'; -import { MockComplaintService } from '../../mocks/mock-complaint.service'; +import { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service'; import { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module'; import { TranslateModule } from '@ngx-translate/core'; import { FileUploadExercise } from 'app/entities/file-upload-exercise.model'; @@ -35,10 +33,13 @@ import { AssessmentType } from 'app/entities/assessment-type.model'; import { Result } from 'app/entities/result.model'; import { ModelingAssessmentModule } from 'app/exercises/modeling/assess/modeling-assessment.module'; import { routes } from 'app/exercises/file-upload/assess/file-upload-assessment.route'; -import { Course } from 'app/entities/course.model'; import { By } from '@angular/platform-browser'; +import { throwError } from 'rxjs'; +import { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route'; +import { Participation, ParticipationType } from 'app/entities/participation/participation.model'; chai.use(sinonChai); + const expect = chai.expect; describe('FileUploadAssessmentComponent', () => { @@ -48,9 +49,8 @@ describe('FileUploadAssessmentComponent', () => { let getFileUploadSubmissionForExerciseWithoutAssessmentStub: SinonStub; let debugElement: DebugElement; let router: Router; - let location: Location; + const activatedRouteMock: MockActivatedRoute = new MockActivatedRoute(); - const course = { id: 5 } as Course; const exercise = { id: 20, type: ExerciseType.FILE_UPLOAD } as FileUploadExercise; beforeEach(async () => { @@ -85,7 +85,6 @@ describe('FileUploadAssessmentComponent', () => { comp.exercise = exercise; debugElement = fixture.debugElement; router = debugElement.injector.get(Router); - location = debugElement.injector.get(Location); fileUploadSubmissionService = TestBed.inject(FileUploadSubmissionService); getFileUploadSubmissionForExerciseWithoutAssessmentStub = stub(fileUploadSubmissionService, 'getFileUploadSubmissionForExerciseWithoutAssessment'); @@ -98,6 +97,9 @@ describe('FileUploadAssessmentComponent', () => { }); it('AssessNextButton should be visible', fakeAsync(() => { + activatedRouteMock.testParams = { exerciseId: 1, submissionId: 'new' }; + getFileUploadSubmissionForExerciseWithoutAssessmentStub.returns(throwError({ status: 404 })); + // set all attributes for comp comp.ngOnInit(); tick(); @@ -109,6 +111,7 @@ describe('FileUploadAssessmentComponent', () => { submitted: true, type: SubmissionType.MANUAL, submissionDate: moment('2019-07-09T10:47:33.244Z'), + participation: ({ type: ParticipationType.STUDENT, exercise } as unknown) as Participation, } as FileUploadSubmission; comp.result = new Result(); comp.result.id = 2374; @@ -123,11 +126,17 @@ describe('FileUploadAssessmentComponent', () => { comp.result.assessmentType = AssessmentType.MANUAL; comp.result.exampleResult = false; comp.result.hasComplaint = false; + comp.submission.result = comp.result; + comp.submission.participation.submissions = [comp.submission]; + comp.submission.participation.results = [comp.submission.result]; comp.isAssessor = true; comp.isAtLeastInstructor = true; comp.assessmentsAreValid = true; - const unassessedSubmission = { submissionExerciseType: SubmissionExerciseType.FILE_UPLOAD, id: 2279, submitted: true, type: 'MANUAL' }; + comp.isLoading = false; fixture.detectChanges(); + + const assessNextButton = debugElement.query(By.css('#assessNextButton')); + expect(assessNextButton).to.exist; })); }); diff --git a/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-detail.component.spec.ts b/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-detail.component.spec.ts index 76b5b9e52acd..c19a0d6f5792 100644 --- a/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-detail.component.spec.ts +++ b/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-detail.component.spec.ts @@ -1,24 +1,21 @@ -/* tslint:disable max-line-length */ import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { ActivatedRoute } from '@angular/router'; import { DebugElement } from '@angular/core'; import { of } from 'rxjs'; - import { ArtemisTestModule } from '../../test.module'; import { FileUploadExerciseDetailComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-detail.component'; import { By } from '@angular/platform-browser'; - import * as sinonChai from 'sinon-chai'; import * as chai from 'chai'; -import { fileUploadExercise, MockFileUploadExerciseService } from '../../mocks/mock-file-upload-exercise.service'; +import { fileUploadExercise, MockFileUploadExerciseService } from '../../helpers/mocks/service/mock-file-upload-exercise.service'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { AlertService } from 'app/core/alert/alert.service'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { RouterTestingModule } from '@angular/router/testing'; import { TranslateModule } from '@ngx-translate/core'; import { ArtemisAssessmentSharedModule } from 'app/assessment/assessment-shared.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { CookieService } from 'ngx-cookie-service'; import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; @@ -27,56 +24,53 @@ import { AssessmentInstructionsModule } from 'app/assessment/assessment-instruct chai.use(sinonChai); const expect = chai.expect; -describe('Component Tests', () => { - describe('FileUploadExercise Management Detail Component', () => { - let comp: FileUploadExerciseDetailComponent; - let fixture: ComponentFixture; - let debugElement: DebugElement; +describe('FileUploadExercise Management Detail Component', () => { + let comp: FileUploadExerciseDetailComponent; + let fixture: ComponentFixture; + let debugElement: DebugElement; - const route = ({ - data: of({ fileUploadExercise: fileUploadExercise }), - params: of({ exerciseId: 2 }), - } as any) as ActivatedRoute; + const route = ({ + data: of({ fileUploadExercise }), + params: of({ exerciseId: 2 }), + } as any) as ActivatedRoute; - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [ArtemisTestModule, ArtemisSharedModule, ArtemisAssessmentSharedModule, RouterTestingModule, TranslateModule.forRoot(), AssessmentInstructionsModule], - declarations: [FileUploadExerciseDetailComponent], - providers: [ - JhiLanguageHelper, - AlertService, - { provide: ActivatedRoute, useValue: route }, - { provide: FileUploadExerciseService, useClass: MockFileUploadExerciseService }, - { provide: LocalStorageService, useClass: MockSyncStorage }, - { provide: SessionStorageService, useClass: MockSyncStorage }, - { provide: CookieService, useClass: MockCookieService }, - ], - }) - .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } }) - .compileComponents(); - fixture = TestBed.createComponent(FileUploadExerciseDetailComponent); - comp = fixture.componentInstance; - debugElement = fixture.debugElement; - }); - - describe('Title should contain exercise id and description list', () => { - it('Should call load all on init', fakeAsync(() => { - comp.ngOnInit(); + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule, ArtemisSharedModule, ArtemisAssessmentSharedModule, RouterTestingModule, TranslateModule.forRoot(), AssessmentInstructionsModule], + declarations: [FileUploadExerciseDetailComponent], + providers: [ + JhiLanguageHelper, + AlertService, + { provide: ActivatedRoute, useValue: route }, + { provide: FileUploadExerciseService, useClass: MockFileUploadExerciseService }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: CookieService, useClass: MockCookieService }, + ], + }) + .overrideModule(ArtemisTestModule, { set: { declarations: [], exports: [] } }) + .compileComponents(); + fixture = TestBed.createComponent(FileUploadExerciseDetailComponent); + comp = fixture.componentInstance; + debugElement = fixture.debugElement; + }); - tick(); + describe('Title should contain exercise id and description list', () => { + it('Should call load all on init', fakeAsync(() => { + comp.ngOnInit(); + tick(); - expect(comp.fileUploadExercise).to.equal(fileUploadExercise); + expect(comp.fileUploadExercise).to.equal(fileUploadExercise); - fixture.detectChanges(); + fixture.detectChanges(); - const title = debugElement.query(By.css('h2')); - expect(title).to.exist; - const h2: HTMLElement = title.nativeElement; - expect(h2.textContent!.endsWith(fileUploadExercise.id.toString())).to.be.true; + const title = debugElement.query(By.css('h2')); + expect(title).to.exist; + const h2: HTMLElement = title.nativeElement; + expect(h2.textContent!.endsWith(fileUploadExercise.id.toString())).to.be.true; - const descList = debugElement.query(By.css('dl')); - expect(descList).to.exist; - })); - }); + const descList = debugElement.query(By.css('dl')); + expect(descList).to.exist; + })); }); }); diff --git a/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-update.component.spec.ts b/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-update.component.spec.ts new file mode 100644 index 000000000000..ce7efe0f0142 --- /dev/null +++ b/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise-update.component.spec.ts @@ -0,0 +1,66 @@ +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { FileUploadExerciseUpdateComponent } from 'app/exercises/file-upload/manage/file-upload-exercise-update.component'; +import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; +import { FileUploadExercise } from 'app/entities/file-upload-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { MockFileUploadExerciseService } from '../../helpers/mocks/service/mock-file-upload-exercise.service'; + +describe('FileUploadExercise Management Update Component', () => { + let comp: FileUploadExerciseUpdateComponent; + let fixture: ComponentFixture; + let service: FileUploadExerciseService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [FileUploadExerciseUpdateComponent], + providers: [ + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: FileUploadExerciseService, useClass: MockFileUploadExerciseService }, + ], + }) + .overrideTemplate(FileUploadExerciseUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(FileUploadExerciseUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(FileUploadExerciseService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new FileUploadExercise(); + entity.id = 123; + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.fileUploadExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity, 123); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new FileUploadExercise(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.fileUploadExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); +}); diff --git a/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise.component.spec.ts b/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise.component.spec.ts new file mode 100644 index 000000000000..4ae7c29de349 --- /dev/null +++ b/src/test/javascript/spec/component/file-upload-exercise/file-upload-exercise.component.spec.ts @@ -0,0 +1,65 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { FileUploadExerciseComponent } from 'app/exercises/file-upload/manage/file-upload-exercise.component'; +import { FileUploadExercise } from 'app/entities/file-upload-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { TranslateService } from '@ngx-translate/core'; +import { Course } from 'app/entities/course.model'; +import { CourseExerciseService } from 'app/course/manage/course-management.service'; + +describe('FileUploadExercise Management Component', () => { + let comp: FileUploadExerciseComponent; + let fixture: ComponentFixture; + let service: CourseExerciseService; + + const course: Course = { id: 123 } as Course; + const fileUploadExercise = new FileUploadExercise(course); + fileUploadExercise.id = 456; + const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [FileUploadExerciseComponent], + providers: [ + { provide: ActivatedRoute, useValue: route }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }) + .overrideTemplate(FileUploadExerciseComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(FileUploadExerciseComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CourseExerciseService); + }); + + it('Should call loadExercises on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'findAllFileUploadExercisesForCourse').and.returnValue( + of( + new HttpResponse({ + body: [fileUploadExercise], + headers, + }), + ), + ); + + // WHEN + comp.course = course; + comp.ngOnInit(); + + // THEN + expect(service.findAllFileUploadExercisesForCourse).toHaveBeenCalled(); + expect(comp.fileUploadExercises[0]).toEqual(fileUploadExercise); + }); +}); diff --git a/src/test/javascript/spec/component/file-upload-submission/file-upload-result.spec.ts b/src/test/javascript/spec/component/file-upload-submission/file-upload-result.component.spec.ts similarity index 90% rename from src/test/javascript/spec/component/file-upload-submission/file-upload-result.spec.ts rename to src/test/javascript/spec/component/file-upload-submission/file-upload-result.component.spec.ts index 19310d53e2d6..b5b1a32d4fb8 100644 --- a/src/test/javascript/spec/component/file-upload-submission/file-upload-result.spec.ts +++ b/src/test/javascript/spec/component/file-upload-submission/file-upload-result.component.spec.ts @@ -5,13 +5,12 @@ import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; import { Result } from 'app/entities/result.model'; import { ArtemisSharedModule } from 'app/shared/shared.module'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { DebugElement } from '@angular/core'; import { By } from '@angular/platform-browser'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { NgxDatatableModule } from '@swimlane/ngx-datatable'; -import { FileUploadSubmissionComponent } from 'app/exercises/file-upload/participate/file-upload-submission.component'; import { TranslateModule } from '@ngx-translate/core'; import { FileUploadResultComponent } from 'app/exercises/file-upload/participate/file-upload-result.component'; import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module'; @@ -20,7 +19,7 @@ import { Feedback } from 'app/entities/feedback.model'; chai.use(sinonChai); const expect = chai.expect; -describe('FileUploadSubmissionComponent', () => { +describe('FileUploadResultComponent', () => { let comp: FileUploadResultComponent; let fixture: ComponentFixture; let debugElement: DebugElement; @@ -63,6 +62,7 @@ describe('FileUploadSubmissionComponent', () => { const groupedFeedbackElements = debugElement.query(By.css('div')); expect(groupedFeedbackElements).to.exist; + // exactly two feedback items are displayed expect(groupedFeedbackElements.childNodes.length).to.be.equal(2); }); diff --git a/src/test/javascript/spec/component/file-upload-submission/file-upload-submission.spec.ts b/src/test/javascript/spec/component/file-upload-submission/file-upload-submission.component.spec.ts similarity index 94% rename from src/test/javascript/spec/component/file-upload-submission/file-upload-submission.spec.ts rename to src/test/javascript/spec/component/file-upload-submission/file-upload-submission.component.spec.ts index 39930b0421fd..0e8721bb42f8 100644 --- a/src/test/javascript/spec/component/file-upload-submission/file-upload-submission.spec.ts +++ b/src/test/javascript/spec/component/file-upload-submission/file-upload-submission.component.spec.ts @@ -4,27 +4,26 @@ import { AccountService } from 'app/core/auth/account.service'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; import { MockComponent } from 'ng-mocks'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { Router } from '@angular/router'; import { ResizableInstructionsComponent } from 'app/exercises/text/assess/resizable-instructions/resizable-instructions.component'; import { DebugElement } from '@angular/core'; import { By } from '@angular/platform-browser'; -import { MockAccountService } from '../../mocks/mock-account.service'; -import { Location } from '@angular/common'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { ComplaintService } from 'app/complaints/complaint.service'; -import { MockComplaintService } from '../../mocks/mock-complaint.service'; +import { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service'; import { NgxDatatableModule } from '@swimlane/ngx-datatable'; -import { fileUploadSubmissionRoute, routes } from 'app/exercises/file-upload/participate/file-upload-participation.route'; +import { routes } from 'app/exercises/file-upload/participate/file-upload-participation.route'; import { FileUploadSubmissionComponent } from 'app/exercises/file-upload/participate/file-upload-submission.component'; import { MomentModule } from 'ngx-moment'; -import { createFileUploadSubmission, MockFileUploadSubmissionService } from '../../mocks/mock-file-upload-submission.service'; +import { createFileUploadSubmission, MockFileUploadSubmissionService } from '../../helpers/mocks/service/mock-file-upload-submission.service'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { fileUploadExercise } from '../../mocks/mock-file-upload-exercise.service'; +import { fileUploadExercise } from '../../helpers/mocks/service/mock-file-upload-exercise.service'; import { MAX_SUBMISSION_FILE_SIZE } from 'app/shared/constants/input.constants'; import { TranslateModule } from '@ngx-translate/core'; import * as sinon from 'sinon'; @@ -51,7 +50,6 @@ describe('FileUploadSubmissionComponent', () => { let fixture: ComponentFixture; let debugElement: DebugElement; let router: Router; - let location: Location; let fileUploaderService: FileUploaderService; let jhiAlertService: AlertService; let fileUploadSubmissionService: FileUploadSubmissionService; @@ -95,7 +93,6 @@ describe('FileUploadSubmissionComponent', () => { comp = fixture.componentInstance; debugElement = fixture.debugElement; router = debugElement.injector.get(Router); - location = debugElement.injector.get(Location); router.initialNavigation(); fileUploaderService = TestBed.inject(FileUploaderService); jhiAlertService = TestBed.inject(AlertService); diff --git a/src/test/javascript/spec/component/guided-tour/guided-tour.component.spec.ts b/src/test/javascript/spec/component/guided-tour/guided-tour.component.spec.ts index 64daea4c9812..cd711c1fcd83 100644 --- a/src/test/javascript/spec/component/guided-tour/guided-tour.component.spec.ts +++ b/src/test/javascript/spec/component/guided-tour/guided-tour.component.spec.ts @@ -1,16 +1,15 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; -import { DebugElement, NO_ERRORS_SCHEMA } from '@angular/core'; -import { ComponentFixture, TestBed, inject, fakeAsync } from '@angular/core/testing'; -import { Router } from '@angular/router'; +import { NO_ERRORS_SCHEMA } from '@angular/core'; +import { ComponentFixture, TestBed } from '@angular/core/testing'; import { RouterTestingModule } from '@angular/router/testing'; import { CookieService } from 'ngx-cookie-service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { of } from 'rxjs'; import { TranslateService } from '@ngx-translate/core'; import { ArtemisTestModule } from '../../test.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { TextTourStep } from 'app/guided-tour/guided-tour-step.model'; import { GuidedTour } from 'app/guided-tour/guided-tour.model'; import { GuidedTourComponent } from 'app/guided-tour/guided-tour.component'; @@ -19,7 +18,7 @@ import { Orientation, OverlayPosition, ResetParticipation } from 'app/guided-tou import { DeviceDetectorService } from 'ngx-device-detector'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { By } from '@angular/platform-browser'; -import { MockTranslateService } from '../../mocks/mock-translate.service'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; chai.use(sinonChai); const expect = chai.expect; @@ -61,9 +60,7 @@ describe('GuidedTourComponent', () => { let guidedTourComponent: GuidedTourComponent; let guidedTourComponentFixture: ComponentFixture; - let guidedTourDebugElement: DebugElement; let guidedTourService: GuidedTourService; - let router: Router; beforeEach(() => { TestBed.configureTestingModule({ @@ -92,9 +89,7 @@ describe('GuidedTourComponent', () => { .then(() => { guidedTourComponentFixture = TestBed.createComponent(GuidedTourComponent); guidedTourComponent = guidedTourComponentFixture.componentInstance; - guidedTourDebugElement = guidedTourComponentFixture.debugElement; guidedTourService = TestBed.inject(GuidedTourService); - router = TestBed.inject(Router); }); }); diff --git a/src/test/javascript/spec/component/instructor-dashboard/instructor-exercise-dashboard.spec.ts b/src/test/javascript/spec/component/instructor-dashboard/instructor-exercise-dashboard.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/instructor-dashboard/instructor-exercise-dashboard.spec.ts rename to src/test/javascript/spec/component/instructor-dashboard/instructor-exercise-dashboard.component.spec.ts diff --git a/src/test/javascript/spec/component/lecture/lecture-attachments.spec.ts b/src/test/javascript/spec/component/lecture/lecture-attachments.component.spec.ts similarity index 99% rename from src/test/javascript/spec/component/lecture/lecture-attachments.spec.ts rename to src/test/javascript/spec/component/lecture/lecture-attachments.component.spec.ts index dbed8a68f517..429ad2bdf12b 100644 --- a/src/test/javascript/spec/component/lecture/lecture-attachments.spec.ts +++ b/src/test/javascript/spec/component/lecture/lecture-attachments.component.spec.ts @@ -150,7 +150,7 @@ describe('LectureAttachmentsComponent', () => { expect(comp.attachments.length).to.equal(3); })); - it('should not accept too large file', fakeAsync((done: Function) => { + it('should not accept too large file', fakeAsync(() => { fixture.detectChanges(); const addAttachmentButton = fixture.debugElement.query(By.css('#add-attachment')); expect(comp.attachmentToBeCreated).to.be.undefined; diff --git a/src/test/javascript/spec/component/list-of-complaints/list-of-complaints.spec.ts b/src/test/javascript/spec/component/list-of-complaints/list-of-complaints.component.spec.ts similarity index 94% rename from src/test/javascript/spec/component/list-of-complaints/list-of-complaints.spec.ts rename to src/test/javascript/spec/component/list-of-complaints/list-of-complaints.component.spec.ts index 91256db2e721..731d3938a3bc 100644 --- a/src/test/javascript/spec/component/list-of-complaints/list-of-complaints.spec.ts +++ b/src/test/javascript/spec/component/list-of-complaints/list-of-complaints.component.spec.ts @@ -5,11 +5,11 @@ import { ArtemisSharedModule } from 'app/shared/shared.module'; import { RouterTestingModule } from '@angular/router/testing'; import { SortByModule } from 'app/shared/pipes/sort-by.module'; import { AlertService } from 'app/core/alert/alert.service'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { ComplaintService } from 'app/complaints/complaint.service'; import { DifferencePipe } from 'ngx-moment'; import { ActivatedRoute } from '@angular/router'; -import { MockActivatedRoute } from '../../helpers/mock-route.service'; +import { MockActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route'; import { ListOfComplaintsComponent } from 'app/complaints/list-of-complaints/list-of-complaints.component'; describe('ListOfComplaintsComponent', () => { diff --git a/src/test/javascript/spec/component/markdown-editor/gradingInstruction-command.spec.ts b/src/test/javascript/spec/component/markdown-editor/gradingInstruction-command.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/markdown-editor/gradingInstruction-command.spec.ts rename to src/test/javascript/spec/component/markdown-editor/gradingInstruction-command.component.spec.ts diff --git a/src/test/javascript/spec/component/markdown-editor/katex-command.spec.ts b/src/test/javascript/spec/component/markdown-editor/katex-command.spec.ts index 95574b18157e..271c5243d45f 100644 --- a/src/test/javascript/spec/component/markdown-editor/katex-command.spec.ts +++ b/src/test/javascript/spec/component/markdown-editor/katex-command.spec.ts @@ -1,4 +1,3 @@ -/* tslint:disable:no-unused-expression */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TranslateModule } from '@ngx-translate/core'; import * as chai from 'chai'; diff --git a/src/test/javascript/spec/component/modeling-assessment-editor/modeling-assessment-editor.component.spec.ts b/src/test/javascript/spec/component/modeling-assessment-editor/modeling-assessment-editor.component.spec.ts index ecf8fba98e4f..816e86c692ca 100644 --- a/src/test/javascript/spec/component/modeling-assessment-editor/modeling-assessment-editor.component.spec.ts +++ b/src/test/javascript/spec/component/modeling-assessment-editor/modeling-assessment-editor.component.spec.ts @@ -3,19 +3,18 @@ import { TranslateModule } from '@ngx-translate/core'; import { ArtemisTestModule } from '../../test.module'; import { By } from '@angular/platform-browser'; -import { mockedActivatedRoute } from '../../helpers/mock-activated-route-query-param-map'; +import { mockedActivatedRoute } from '../../helpers/mocks/activated-route/mock-activated-route-query-param-map'; import { ActivatedRoute, convertToParamMap, ParamMap } from '@angular/router'; import { Mutable } from '../../helpers/mutable'; import { BehaviorSubject } from 'rxjs'; import { RouterTestingModule } from '@angular/router/testing'; -import { User } from 'app/core/user/user.model'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../../helpers/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { AssessmentLayoutComponent } from 'app/assessment/assessment-layout/assessment-layout.component'; import { AssessmentHeaderComponent } from 'app/assessment/assessment-header/assessment-header.component'; import { Course } from 'app/entities/course.model'; -import { ModelingExercise } from 'app/entities/modeling-exercise.model'; +import { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model'; import { ModelingAssessmentEditorComponent } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.component'; import { ArtemisModelingAssessmentEditorModule } from 'app/exercises/modeling/assess/modeling-assessment-editor/modeling-assessment-editor.module'; @@ -36,8 +35,8 @@ describe('ModelingAssessmentEditorComponent', () => { fixture = TestBed.createComponent(ModelingAssessmentEditorComponent); component = fixture.componentInstance; mockAuth = (fixture.debugElement.injector.get(AccountService) as any) as MockAccountService; - mockAuth.hasAnyAuthorityDirectSpy.and.returnValue(false); - mockAuth.identitySpy.and.returnValue(Promise.resolve(new User())); + mockAuth.hasAnyAuthorityDirect([]); + mockAuth.identity(); fixture.detectChanges(); }); @@ -60,8 +59,10 @@ describe('ModelingAssessmentEditorComponent', () => { }); it('should propagate isAtLeastInstructor', () => { - component.modelingExercise = new ModelingExercise('ClassDiagram', new Course()); - mockAuth.isAtLeastInstructorInCourseSpy.and.returnValue(true); + const course = new Course(); + course.isAtLeastInstructor = true; + component.modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course); + mockAuth.isAtLeastInstructorInCourse(course); component['checkPermissions'](); fixture.detectChanges(); expect(component.isAtLeastInstructor).toBeTruthy(); @@ -69,7 +70,8 @@ describe('ModelingAssessmentEditorComponent', () => { let assessmentLayoutComponent: AssessmentHeaderComponent = fixture.debugElement.query(By.directive(AssessmentLayoutComponent)).componentInstance; expect(assessmentLayoutComponent.isAtLeastInstructor).toBeTruthy(); - mockAuth.isAtLeastInstructorInCourseSpy.and.returnValue(false); + course.isAtLeastInstructor = false; + mockAuth.isAtLeastInstructorInCourse(course); component['checkPermissions'](); fixture.detectChanges(); expect(component.isAtLeastInstructor).toBeFalsy(); diff --git a/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-detail.component.spec.ts b/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-detail.component.spec.ts new file mode 100644 index 000000000000..38b3bd08d34f --- /dev/null +++ b/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-detail.component.spec.ts @@ -0,0 +1,51 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { ModelingExerciseDetailComponent } from 'app/exercises/modeling/manage/modeling-exercise-detail.component'; +import { ModelingExercise } from 'app/entities/modeling-exercise.model'; +import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; + +describe('ModelingExercise Management Detail Component', () => { + let comp: ModelingExerciseDetailComponent; + let fixture: ComponentFixture; + let modelingExerciseService: ModelingExerciseService; + + const modelingExercise = { id: 123 } as ModelingExercise; + const route = ({ params: of({ exerciseId: modelingExercise.id }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ModelingExerciseDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }], + }) + .overrideTemplate(ModelingExerciseDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(ModelingExerciseDetailComponent); + comp = fixture.componentInstance; + modelingExerciseService = fixture.debugElement.injector.get(ModelingExerciseService); + }); + + it('Should load exercise on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(modelingExerciseService, 'find').and.returnValue( + of( + new HttpResponse({ + body: modelingExercise, + headers, + }), + ), + ); + + // WHEN + comp.ngOnInit(); + + // THEN + expect(modelingExerciseService.find).toHaveBeenCalled(); + expect(comp.modelingExercise).toEqual(modelingExercise); + }); +}); diff --git a/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-update.component.spec.ts b/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-update.component.spec.ts new file mode 100644 index 000000000000..2c6ed15cba9a --- /dev/null +++ b/src/test/javascript/spec/component/modeling-exercise/modeling-exercise-update.component.spec.ts @@ -0,0 +1,64 @@ +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { ModelingExerciseUpdateComponent } from 'app/exercises/modeling/manage/modeling-exercise-update.component'; +import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; +import { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; + +describe('ModelingExercise Management Update Component', () => { + let comp: ModelingExerciseUpdateComponent; + let fixture: ComponentFixture; + let service: ModelingExerciseService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ModelingExerciseUpdateComponent], + providers: [ + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + ], + }) + .overrideTemplate(ModelingExerciseUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ModelingExerciseUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ModelingExerciseService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new ModelingExercise(UMLDiagramType.ActivityDiagram); + entity.id = 123; + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.modelingExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity, {}); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new ModelingExercise(UMLDiagramType.ClassDiagram); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.modelingExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); +}); diff --git a/src/test/javascript/spec/component/modeling-exercise/modeling-exercise.component.spec.ts b/src/test/javascript/spec/component/modeling-exercise/modeling-exercise.component.spec.ts new file mode 100644 index 000000000000..bb82356180e9 --- /dev/null +++ b/src/test/javascript/spec/component/modeling-exercise/modeling-exercise.component.spec.ts @@ -0,0 +1,65 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; +import { TranslateService } from '@ngx-translate/core'; + +import { ArtemisTestModule } from '../../test.module'; +import { ModelingExerciseComponent } from 'app/exercises/modeling/manage/modeling-exercise.component'; +import { ModelingExercise, UMLDiagramType } from 'app/entities/modeling-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { CourseExerciseService } from 'app/course/manage/course-management.service'; +import { Course } from 'app/entities/course.model'; + +describe('ModelingExercise Management Component', () => { + let comp: ModelingExerciseComponent; + let fixture: ComponentFixture; + let courseExerciseService: CourseExerciseService; + + const course: Course = { id: 123 } as Course; + const modelingExercise = new ModelingExercise(UMLDiagramType.ClassDiagram, course); + modelingExercise.id = 456; + const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ModelingExerciseComponent], + providers: [ + { provide: ActivatedRoute, useValue: route }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }) + .overrideTemplate(ModelingExerciseComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ModelingExerciseComponent); + comp = fixture.componentInstance; + courseExerciseService = fixture.debugElement.injector.get(CourseExerciseService); + }); + + it('Should call loadExercises on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(courseExerciseService, 'findAllModelingExercisesForCourse').and.returnValue( + of( + new HttpResponse({ + body: [modelingExercise], + headers, + }), + ), + ); + + // WHEN + comp.course = course; + comp.ngOnInit(); + + // THEN + expect(courseExerciseService.findAllModelingExercisesForCourse).toHaveBeenCalled(); + expect(comp.modelingExercises[0]).toEqual(modelingExercise); + }); +}); diff --git a/src/test/javascript/spec/component/modeling-submission/modeling-submission.component.spec.ts b/src/test/javascript/spec/component/modeling-submission/modeling-submission.component.spec.ts index 2bbcfeff28c3..4b253c24de91 100644 --- a/src/test/javascript/spec/component/modeling-submission/modeling-submission.component.spec.ts +++ b/src/test/javascript/spec/component/modeling-submission/modeling-submission.component.spec.ts @@ -1,4 +1,3 @@ -/* tslint:disable max-line-length */ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { of, throwError } from 'rxjs'; @@ -6,9 +5,9 @@ import { ArtemisTestModule } from '../../test.module'; import { ModelingSubmissionComponent } from 'app/exercises/modeling/participate/modeling-submission.component'; import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; import { ModelingSubmission } from 'app/entities/modeling-submission.model'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { CookieService } from 'ngx-cookie-service'; import { TranslateModule } from '@ngx-translate/core'; @@ -19,8 +18,8 @@ import { DebugElement } from '@angular/core'; import { By } from '@angular/platform-browser'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; -import { MockAlertService } from '../../helpers/mock-alert.service'; -import { MockComplaintService } from '../../mocks/mock-complaint.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; +import { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service'; import { AlertService } from 'app/core/alert/alert.service'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module'; @@ -186,7 +185,7 @@ describe('Component Tests', () => { it('should navigate to access denied page on 403 error status', () => { sinon.replace(service, 'getLatestSubmissionForModelingEditor', sinon.fake.returns(throwError({ status: 403 }))); const spy = stub(router, 'navigate'); - spy.returns(new Promise((resolve) => true)); + spy.returns(new Promise(() => true)); fixture.detectChanges(); expect(spy.called).to.be.true; }); diff --git a/src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.spec.ts b/src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.component.spec.ts similarity index 93% rename from src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.spec.ts rename to src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.component.spec.ts index f27f95eb4398..584797e020ed 100644 --- a/src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.spec.ts +++ b/src/test/javascript/spec/component/overview/course-exercises/course-exercise-row.component.spec.ts @@ -8,18 +8,18 @@ import { ParticipationWebsocketService } from 'app/overview/participation-websoc import { ArtemisTestModule } from '../../../test.module'; import { TranslateModule } from '@ngx-translate/core'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; -import { MockOrionConnectorService } from '../../../mocks/mock-orion-connector.service'; -import { MockCourseExerciseService } from '../../../mocks/mock-course-exercise.service'; +import { MockOrionConnectorService } from '../../../helpers/mocks/service/mock-orion-connector.service'; +import { MockCourseExerciseService } from '../../../helpers/mocks/service/mock-course-exercise.service'; import { AlertService } from 'app/core/alert/alert.service'; -import { MockAlertService } from '../../../helpers/mock-alert.service'; -import { MockParticipationWebsocketService } from '../../../mocks/mock-participation-websocket.service'; +import { MockAlertService } from '../../../helpers/mocks/service/mock-alert.service'; +import { MockParticipationWebsocketService } from '../../../helpers/mocks/service/mock-participation-websocket.service'; import { Result } from 'app/entities/result.model'; import { DeviceDetectorService } from 'ngx-device-detector'; import { of } from 'rxjs'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../../../mocks/mock-account.service'; +import { MockAccountService } from '../../../helpers/mocks/service/mock-account.service'; import * as moment from 'moment'; -import { MockCourseService } from '../../../mocks/mock-course.service'; +import { MockCourseService } from '../../../helpers/mocks/service/mock-course.service'; import { Exercise, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model'; import { ArtemisCoursesModule } from 'app/overview/courses.module'; import { InitializationState } from 'app/entities/participation/participation.model'; @@ -28,7 +28,8 @@ import { CourseExerciseRowComponent } from 'app/overview/course-exercises/course import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; import { CourseExerciseService, CourseManagementService } from 'app/course/manage/course-management.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; -import { MockSyncStorage } from '../../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service'; +import { Course } from 'app/entities/course.model'; chai.use(sinonChai); const expect = chai.expect; @@ -60,6 +61,7 @@ describe('CourseExerciseRowComponent', () => { .then(() => { fixture = TestBed.createComponent(CourseExerciseRowComponent); comp = fixture.componentInstance; + comp.course = { id: 123, isAtLeastInstructor: true } as Course; debugElement = fixture.debugElement; participationWebsocketService = debugElement.injector.get(ParticipationWebsocketService); getAllParticipationsStub = stub(participationWebsocketService, 'getParticipationForExercise'); diff --git a/src/test/javascript/spec/component/overview/course-statistics/course-statistics.spec.ts b/src/test/javascript/spec/component/overview/course-statistics/course-statistics.component.spec.ts similarity index 96% rename from src/test/javascript/spec/component/overview/course-statistics/course-statistics.spec.ts rename to src/test/javascript/spec/component/overview/course-statistics/course-statistics.component.spec.ts index b2d59192d532..22959ac32fbe 100644 --- a/src/test/javascript/spec/component/overview/course-statistics/course-statistics.spec.ts +++ b/src/test/javascript/spec/component/overview/course-statistics/course-statistics.component.spec.ts @@ -12,12 +12,11 @@ import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ActivatedRoute } from '@angular/router'; import { By } from '@angular/platform-browser'; import { Course } from 'app/entities/course.model'; -import { MockSyncStorage } from '../../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../../helpers/mocks/service/mock-sync-storage.service'; import { Result } from 'app/entities/result.model'; import { CourseScoreCalculationService } from 'app/overview/course-score-calculation.service'; import { ProgrammingSubmission } from 'app/entities/programming-submission.model'; import { ModelingExercise } from 'app/entities/modeling-exercise.model'; -import { Attachment } from 'app/entities/attachment.model'; import { SubmissionExerciseType } from 'app/entities/submission.model'; import { CourseStatisticsComponent } from 'app/overview/course-statistics/course-statistics.component'; @@ -153,15 +152,6 @@ describe('CourseStatisticsComponent', () => { course.exercises = []; course.presentationScore = 1; - const newAttachment = { - id: 53, - name: 'TestFile', - link: '/api/files/attachments/lecture/4/Mein_Test_PDF3.pdf', - version: 1, - uploadDate: moment('2019-05-07T08:49:59+02:00'), - attachmentType: 'FILE', - } as Attachment; - beforeEach(async () => { return TestBed.configureTestingModule({ imports: [TranslateModule.forRoot(), ArtemisTestModule, TreeviewModule.forRoot(), RouterTestingModule.withRoutes([]), ArtemisSharedModule, ChartsModule], diff --git a/src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.spec.ts b/src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.component.spec.ts similarity index 94% rename from src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.spec.ts rename to src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.component.spec.ts index 2471617efd01..789034c06448 100644 --- a/src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.spec.ts +++ b/src/test/javascript/spec/component/overview/exercise-details/exercise-details-student-actions.component.spec.ts @@ -13,25 +13,25 @@ import { MockComponent } from 'ng-mocks'; import { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module'; import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; import { InitializationState } from 'app/entities/participation/participation.model'; -import { MockFeatureToggleService } from '../../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../../helpers/mocks/service/mock-feature-toggle.service'; import { ExerciseMode, ExerciseType, ParticipationStatus } from 'app/entities/exercise.model'; -import { MockCourseExerciseService } from '../../../mocks/mock-course-exercise.service'; +import { MockCourseExerciseService } from '../../../helpers/mocks/service/mock-course-exercise.service'; import { ExerciseActionButtonComponent } from 'app/overview/exercise-details/exercise-action-button.component'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; import { ArtemisTestModule } from '../../../test.module'; import { JhiAlertService } from 'ng-jhipster'; -import { MockAlertService } from '../../../mocks/mock-alert.service'; +import { MockAlertService } from '../../../helpers/mocks/service/mock-alert.service'; import { ExerciseDetailsStudentActionsComponent } from 'app/overview/exercise-details/exercise-details-student-actions.component'; import { Team } from 'app/entities/team.model'; import { RouterModule } from '@angular/router'; import { ClipboardModule } from 'ngx-clipboard'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../../../mocks/mock-account.service'; +import { MockAccountService } from '../../../helpers/mocks/service/mock-account.service'; import { User } from 'app/core/user/user.model'; import { By } from '@angular/platform-browser'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { ProfileService } from 'app/shared/layouts/profiles/profile.service'; -import { MockProfileService } from '../../../mocks/mock-profile.service'; +import { MockProfileService } from '../../../helpers/mocks/service/mock-profile.service'; import { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model'; chai.use(sinonChai); diff --git a/src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.spec.ts b/src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.component.spec.ts similarity index 93% rename from src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.spec.ts rename to src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.component.spec.ts index 8bf5ed6e07d9..951f71975ad3 100644 --- a/src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.spec.ts +++ b/src/test/javascript/spec/component/overview/exercise-details/programming-exercise-student-ide-actions.component.spec.ts @@ -15,19 +15,19 @@ import { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.mo import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; import { ProgrammingExerciseStudentIdeActionsComponent } from 'app/overview/exercise-details/programming-exercise-student-ide-actions.component'; import { InitializationState } from 'app/entities/participation/participation.model'; -import { MockFeatureToggleService } from '../../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../../helpers/mocks/service/mock-feature-toggle.service'; import { Exercise, ParticipationStatus } from 'app/entities/exercise.model'; -import { MockCourseExerciseService } from '../../../mocks/mock-course-exercise.service'; +import { MockCourseExerciseService } from '../../../helpers/mocks/service/mock-course-exercise.service'; import { ExerciseActionButtonComponent } from 'app/overview/exercise-details/exercise-action-button.component'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; import { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model'; import { ArtemisTestModule } from '../../../test.module'; import { JhiAlertService } from 'ng-jhipster'; -import { MockAlertService } from '../../../mocks/mock-alert.service'; -import { MockOrionConnectorService } from '../../../mocks/mock-orion-connector.service'; +import { MockAlertService } from '../../../helpers/mocks/service/mock-alert.service'; +import { MockOrionConnectorService } from '../../../helpers/mocks/service/mock-orion-connector.service'; import { ArtemisOrionConnector, OrionState } from 'app/shared/orion/orion'; import { OrionModule } from 'app/shared/orion/orion.module'; -import { MockIdeBuildAndTestService } from '../../../mocks/mock-ide-build-and-test.service'; +import { MockIdeBuildAndTestService } from '../../../helpers/mocks/service/mock-ide-build-and-test.service'; import { OrionBuildAndTestService } from 'app/shared/orion/orion-build-and-test.service'; chai.use(sinonChai); diff --git a/src/test/javascript/spec/component/overview/overview.component.spec.ts b/src/test/javascript/spec/component/overview/overview.component.spec.ts index b3f43b34a1f9..2100e957e489 100644 --- a/src/test/javascript/spec/component/overview/overview.component.spec.ts +++ b/src/test/javascript/spec/component/overview/overview.component.spec.ts @@ -2,28 +2,26 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; -import { Router } from '@angular/router'; import { of } from 'rxjs'; import { CookieService } from 'ngx-cookie-service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { ArtemisTestModule } from '../../test.module'; import { GuidedTourService } from 'app/guided-tour/guided-tour.service'; import { GuidedTourComponent } from 'app/guided-tour/guided-tour.component'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { AccountService } from 'app/core/auth/account.service'; import { DeviceDetectorService } from 'ngx-device-detector'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { RouterTestingModule } from '@angular/router/testing'; import { courseOverviewTour } from 'app/guided-tour/tours/course-overview-tour'; -import { CourseExerciseService } from 'app/course/manage/course-management.service'; import { CoursesComponent } from 'app/overview/courses.component'; -import { TranslateTestingModule } from '../../mocks/mock-translate.service'; +import { TranslateTestingModule } from '../../helpers/mocks/service/mock-translate.service'; import { NavbarComponent } from 'app/shared/layouts/navbar/navbar.component'; import { ActiveMenuDirective } from 'app/shared/layouts/navbar/active-menu.directive'; import { NotificationSidebarComponent } from 'app/shared/layouts/notification-sidebar/notification-sidebar.component'; import { User } from 'app/core/user/user.model'; -import { MockHasAnyAuthorityDirective } from '../../mocks/mock-has-any-authority.directive'; +import { MockHasAnyAuthorityDirective } from '../../helpers/mocks/directive/mock-has-any-authority.directive'; import { ArtemisSharedPipesModule } from 'app/shared/pipes/shared-pipes.module'; import { ArtemisSharedCommonModule } from 'app/shared/shared-common.module'; import { CourseCardComponent } from 'app/overview/course-card.component'; @@ -47,13 +45,10 @@ describe('Courses Component', () => { let navBarComponentFixture: ComponentFixture; let courseCardComponent: CourseCardComponent; let courseCardComponentFixture: ComponentFixture; - let footerComponent: FooterComponent; let footerComponentFixture: ComponentFixture; let guidedTourService: GuidedTourService; - let courseExerciseService: CourseExerciseService; let exerciseService: ExerciseService; - let router: Router; beforeEach(() => { TestBed.configureTestingModule({ @@ -90,11 +85,8 @@ describe('Courses Component', () => { guidedTourComponent = guidedTourComponentFixture.componentInstance; navBarComponent = navBarComponentFixture.componentInstance; courseCardComponent = courseCardComponentFixture.componentInstance; - footerComponent = footerComponentFixture.componentInstance; - router = TestBed.inject(Router); guidedTourService = TestBed.inject(GuidedTourService); - courseExerciseService = TestBed.inject(CourseExerciseService); exerciseService = TestBed.inject(ExerciseService); spyOn(courseCardComponent, 'displayTotalRelativeScore').and.returnValue(of()); diff --git a/src/test/javascript/spec/component/participation-submission/participation-submission.spec.ts b/src/test/javascript/spec/component/participation-submission/participation-submission.component.spec.ts similarity index 93% rename from src/test/javascript/spec/component/participation-submission/participation-submission.spec.ts rename to src/test/javascript/spec/component/participation-submission/participation-submission.component.spec.ts index ad5717c1259c..ac3d9dc336a4 100644 --- a/src/test/javascript/spec/component/participation-submission/participation-submission.spec.ts +++ b/src/test/javascript/spec/component/participation-submission/participation-submission.component.spec.ts @@ -6,10 +6,10 @@ import * as sinonChai from 'sinon-chai'; import * as moment from 'moment'; import { SinonStub, stub } from 'sinon'; import { ArtemisTestModule } from '../../test.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { MockComponent } from 'ng-mocks'; import { ArtemisSharedModule } from 'app/shared/shared.module'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { Router } from '@angular/router'; import { of } from 'rxjs'; @@ -18,13 +18,12 @@ import { ResizableInstructionsComponent } from 'app/exercises/text/assess/resiza import { AssessmentDetailComponent } from 'app/assessment/assessment-detail/assessment-detail.component'; import { DebugElement } from '@angular/core'; import { By } from '@angular/platform-browser'; -import { MockAccountService } from '../../mocks/mock-account.service'; -import { Location } from '@angular/common'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { ComplaintService } from 'app/complaints/complaint.service'; import { ParticipationSubmissionComponent } from 'app/exercises/shared/participation-submission/participation-submission.component'; import { SubmissionService } from 'app/exercises/shared/submission/submission.service'; -import { MockComplaintService } from '../../mocks/mock-complaint.service'; +import { MockComplaintService } from '../../helpers/mocks/service/mock-complaint.service'; import { NgxDatatableModule } from '@swimlane/ngx-datatable'; import { TranslateModule } from '@ngx-translate/core'; import { ComplaintsForTutorComponent } from 'app/complaints/complaints-for-tutor/complaints-for-tutor.component'; @@ -45,7 +44,6 @@ describe('ParticipationSubmissionComponent', () => { let findAllSubmissionsOfParticipationStub: SinonStub; let debugElement: DebugElement; let router: Router; - let location: Location; beforeEach(async () => { return TestBed.configureTestingModule({ @@ -75,7 +73,6 @@ describe('ParticipationSubmissionComponent', () => { comp.participationId = 1; debugElement = fixture.debugElement; router = debugElement.injector.get(Router); - location = debugElement.injector.get(Location); submissionService = TestBed.inject(SubmissionService); findAllSubmissionsOfParticipationStub = stub(submissionService, 'findAllSubmissionsOfParticipation'); router.initialNavigation(); diff --git a/src/test/javascript/spec/component/participation-submission/participation-submissions-delete-dialog.component.spec.ts b/src/test/javascript/spec/component/participation-submission/participation-submissions-delete-dialog.component.spec.ts index 3304c107b5b5..8386d001e4c9 100644 --- a/src/test/javascript/spec/component/participation-submission/participation-submissions-delete-dialog.component.spec.ts +++ b/src/test/javascript/spec/component/participation-submission/participation-submissions-delete-dialog.component.spec.ts @@ -1,4 +1,3 @@ -/* tslint:disable max-line-length */ import { ComponentFixture, fakeAsync, inject, TestBed, tick } from '@angular/core/testing'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import { of } from 'rxjs'; diff --git a/src/test/javascript/spec/component/participation/participation.component.spec.ts b/src/test/javascript/spec/component/participation/participation.component.spec.ts index 12d0ff625c66..45f743db117e 100644 --- a/src/test/javascript/spec/component/participation/participation.component.spec.ts +++ b/src/test/javascript/spec/component/participation/participation.component.spec.ts @@ -5,8 +5,8 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisSharedModule } from 'app/shared/shared.module'; -import { MockActivatedRoute } from '../../mocks/mock-activated.route'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; import { ParticipationComponent } from 'app/exercises/shared/participation/participation.component'; import { Course } from 'app/entities/course.model'; @@ -27,7 +27,7 @@ describe('ParticipationComponent', () => { imports: [ArtemisTestModule, ArtemisSharedModule], declarations: [ParticipationComponent], providers: [ - { provide: ActivatedRoute, useClass: MockActivatedRoute }, + { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects }, { provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, ], diff --git a/src/test/javascript/spec/component/programming-assessment/programming-assessment-manual-result-dialog.component.ts b/src/test/javascript/spec/component/programming-assessment/programming-assessment-manual-result-dialog.component.spec.ts similarity index 92% rename from src/test/javascript/spec/component/programming-assessment/programming-assessment-manual-result-dialog.component.ts rename to src/test/javascript/spec/component/programming-assessment/programming-assessment-manual-result-dialog.component.spec.ts index 6b42c76aab8b..f50b46a7dcbb 100644 --- a/src/test/javascript/spec/component/programming-assessment/programming-assessment-manual-result-dialog.component.ts +++ b/src/test/javascript/spec/component/programming-assessment/programming-assessment-manual-result-dialog.component.spec.ts @@ -9,10 +9,10 @@ import { SinonStub, stub } from 'sinon'; import { of } from 'rxjs'; import { ArtemisTestModule } from '../../test.module'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockResultService } from '../../mocks/mock-result.service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockProgrammingExerciseParticipationService } from '../../mocks/mock-programming-exercise-participation.service'; +import { MockResultService } from '../../helpers/mocks/service/mock-result.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { BuildLogService } from 'app/exercises/programming/shared/service/build-log.service'; import { FormDateTimePickerModule } from 'app/shared/date-time-picker/date-time-picker.module'; @@ -36,9 +36,9 @@ import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { Complaint } from 'app/entities/complaint.model'; import { ComplaintService } from 'app/complaints/complaint.service'; import { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; -import { MockRepositoryFileService } from '../../mocks/mock-repository-file.service'; -import { MockExerciseHintService } from '../../mocks/mock-exercise-hint.service'; -import { MockNgbModalService } from '../../mocks/mock-ngb-modal.service'; +import { MockRepositoryFileService } from '../../helpers/mocks/service/mock-repository-file.service'; +import { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service'; +import { MockNgbModalService } from '../../helpers/mocks/service/mock-ngb-modal.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-detail.component.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-detail.component.spec.ts new file mode 100644 index 000000000000..b5bfcf58ea91 --- /dev/null +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-detail.component.spec.ts @@ -0,0 +1,39 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { ProgrammingExerciseDetailComponent } from 'app/exercises/programming/manage/programming-exercise-detail.component'; +import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; + +describe('ProgrammingExercise Management Detail Component', () => { + let comp: ProgrammingExerciseDetailComponent; + let fixture: ComponentFixture; + const programmingExercise = new ProgrammingExercise(); + programmingExercise.id = 123; + const route = ({ data: of({ programmingExercise }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ProgrammingExerciseDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }], + }) + .overrideTemplate(ProgrammingExerciseDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(ProgrammingExerciseDetailComponent); + comp = fixture.componentInstance; + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + + // WHEN + comp.ngOnInit(); + + // THEN + expect(comp.programmingExercise).toEqual(jasmine.objectContaining({ id: 123 })); + }); + }); +}); diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.component.spec.ts similarity index 96% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.component.spec.ts index 558d61d11efd..95ac84d4fb60 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-editable-instruction.component.spec.ts @@ -10,12 +10,12 @@ import * as sinonChai from 'sinon-chai'; import { SinonSpy, SinonStub, spy, stub } from 'sinon'; import { ArtemisTestModule } from '../../test.module'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockResultService } from '../../mocks/mock-result.service'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; +import { MockResultService } from '../../helpers/mocks/service/mock-result.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; import { MarkdownEditorComponent } from 'app/shared/markdown-editor/markdown-editor.component'; -import { MockProgrammingExerciseTestCaseService } from '../../mocks/mock-programming-exercise-test-case.service'; +import { MockProgrammingExerciseTestCaseService } from '../../helpers/mocks/service/mock-programming-exercise-test-case.service'; import { ArtemisProgrammingExerciseInstructionsEditorModule } from 'app/exercises/programming/manage/instructions-editor/programming-exercise-instructions-editor.module'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { Participation } from 'app/entities/participation/participation.model'; import { ResultService } from 'app/exercises/shared/result/result.service'; import { TemplateProgrammingExerciseParticipation } from 'app/entities/participation/template-programming-exercise-participation.model'; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-import.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-import.component.spec.ts similarity index 94% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-import.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-import.component.spec.ts index 4c001f8a717a..6dd05f4ffcce 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-import.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-import.component.spec.ts @@ -12,13 +12,13 @@ import { SortByModule } from 'app/shared/pipes/sort-by.module'; import { DifferencePipe } from 'ngx-moment'; import { FeatureToggleModule } from 'app/shared/feature-toggle/feature-toggle.module'; import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; -import { MockFeatureToggleService } from '../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service'; import { ProgrammingExerciseImportComponent } from 'app/exercises/programming/manage/programming-exercise-import.component'; import { ArtemisSharedCommonModule } from 'app/shared/shared-common.module'; import { ProgrammingExercise, ProgrammingLanguage } from 'app/entities/programming-exercise.model'; import { SearchResult } from 'app/shared/table/pageable-table'; import { ButtonComponent } from 'app/shared/components/button.component'; -import { MockProgrammingExercisePagingService } from '../../mocks/mock-programming-exercise-paging.service'; +import { MockProgrammingExercisePagingService } from '../../helpers/mocks/service/mock-programming-exercise-paging.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.component.spec.ts similarity index 99% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.component.spec.ts index 8f3c03e34197..bdd4092b7db1 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-analysis.component.spec.ts @@ -12,7 +12,7 @@ import { ArtemisProgrammingExerciseInstructionsEditorModule } from 'app/exercise import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { TaskCommand } from 'app/shared/markdown-editor/domainCommands/programming-exercise/task.command'; import { HttpResponse } from '@angular/common/http'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { ExerciseHintService, IExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; import { ProgrammingExerciseInstructionAnalysisComponent } from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.component'; import { ProgrammingExerciseInstructionAnalysisService } from 'app/exercises/programming/manage/instructions-editor/analysis/programming-exercise-instruction-analysis.service'; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-step-wizard.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-step-wizard.component.spec.ts similarity index 91% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-step-wizard.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-step-wizard.component.spec.ts index 69bdfa71c1d5..5b06016db6de 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-step-wizard.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction-step-wizard.component.spec.ts @@ -9,20 +9,18 @@ import * as moment from 'moment'; import { ArtemisTestModule } from '../../test.module'; import { ProgrammingExerciseInstructionStepWizardComponent } from 'app/exercises/programming/shared/instructions-render/step-wizard/programming-exercise-instruction-step-wizard.component'; import { ProgrammingExerciseInstructionService } from 'app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { Task } from 'app/exercises/programming/shared/instructions-render/task/programming-exercise-task.model'; chai.use(sinonChai); const expect = chai.expect; -describe('ProgrammingExerciseInstructionStepWizard', () => { +describe('ProgrammingExerciseInstructionStepWizardComponent', () => { let comp: ProgrammingExerciseInstructionStepWizardComponent; let fixture: ComponentFixture; let debugElement: DebugElement; - let programmingExerciseInstructionService: ProgrammingExerciseInstructionService; - const stepWizardStep = '.stepwizard-step'; beforeEach(async () => { @@ -37,8 +35,6 @@ describe('ProgrammingExerciseInstructionStepWizard', () => { fixture = TestBed.createComponent(ProgrammingExerciseInstructionStepWizardComponent); comp = fixture.componentInstance; debugElement = fixture.debugElement; - - programmingExerciseInstructionService = debugElement.injector.get(ProgrammingExerciseInstructionService); }); }); diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.component.spec.ts similarity index 94% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.component.spec.ts index 4fe5b5e7bad8..3f91ab3650c6 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instruction.component.spec.ts @@ -12,18 +12,18 @@ import { Observable, of, Subject, Subscription, throwError } from 'rxjs'; import { FaIconComponent } from '@fortawesome/angular-fontawesome'; import { ArtemisTestModule } from '../../test.module'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockResultService } from '../../mocks/mock-result.service'; -import { MockRepositoryFileService } from '../../mocks/mock-repository-file.service'; -import { problemStatement, problemStatementBubbleSortFailsHtml, problemStatementBubbleSortNotExecutedHtml } from '../../sample/problemStatement.json'; -import { MockNgbModalService } from '../../mocks/mock-ngb-modal.service'; +import { MockResultService } from '../../helpers/mocks/service/mock-result.service'; +import { MockRepositoryFileService } from '../../helpers/mocks/service/mock-repository-file.service'; +import { problemStatement, problemStatementBubbleSortFailsHtml, problemStatementBubbleSortNotExecutedHtml } from '../../helpers/sample/problemStatement.json'; +import { MockNgbModalService } from '../../helpers/mocks/service/mock-ngb-modal.service'; import { ProgrammingExerciseInstructionStepWizardComponent } from 'app/exercises/programming/shared/instructions-render/step-wizard/programming-exercise-instruction-step-wizard.component'; import { ProgrammingExerciseInstructionService } from 'app/exercises/programming/shared/instructions-render/service/programming-exercise-instruction.service'; import { ProgrammingExerciseTaskExtensionWrapper } from 'app/exercises/programming/shared/instructions-render/extensions/programming-exercise-task.extension'; import { ProgrammingExercisePlantUmlExtensionWrapper } from 'app/exercises/programming/shared/instructions-render/extensions/programming-exercise-plant-uml.extension'; -import { MockProgrammingExerciseParticipationService } from '../../mocks/mock-programming-exercise-participation.service'; +import { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service'; import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { HttpResponse } from '@angular/common/http'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { LocalStorageService } from 'ngx-webstorage'; import { Participation } from 'app/entities/participation/participation.model'; import { ExerciseHintService, IExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; @@ -31,15 +31,16 @@ import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ResultService } from 'app/exercises/shared/result/result.service'; import { RepositoryFileService } from 'app/shared/result/repository.service'; import { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service'; +// eslint-disable-next-line @typescript-eslint/tslint/config import { ProgrammingExerciseInstructionTaskStatusComponent } from 'app/exercises/programming/shared/instructions-render/task/programming-exercise-instruction-task-status.component'; import { Result } from 'app/entities/result.model'; import { Feedback } from 'app/entities/feedback.model'; import { ProgrammingExerciseInstructionComponent } from 'app/exercises/programming/shared/instructions-render/programming-exercise-instruction.component'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { ResultDetailComponent } from 'app/shared/result/result-detail.component'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockExerciseHintService } from '../../mocks/mock-exercise-hint.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service'; chai.use(sinonChai); const expect = chai.expect; @@ -61,7 +62,6 @@ describe('ProgrammingExerciseInstructionComponent', () => { let getHintsForExerciseStub: SinonStub; const exerciseHints = [{ id: 1 }, { id: 2 }]; - const exercise = { id: 1 }; beforeEach(async () => { return TestBed.configureTestingModule({ @@ -109,6 +109,7 @@ describe('ProgrammingExerciseInstructionComponent', () => { }); it('should on participation change clear old subscription for participation results set up new one', () => { + const exercise = { id: 1 }; const oldParticipation = { id: 1 } as Participation; const result = { id: 1 }; const participation = { id: 2, results: [result] } as Participation; @@ -164,8 +165,8 @@ describe('ProgrammingExerciseInstructionComponent', () => { it('should NOT try to fetch README.md from assignment repository if a problemStatement was provided', () => { const result = { id: 1, feedbacks: [] as Feedback[] } as Result; const participation = { id: 2 } as Participation; - const problemStatement = 'lorem ipsum'; - const exercise = { id: 3, course: { id: 4 }, problemStatement } as ProgrammingExercise; + const problemstatement = 'lorem ipsum'; + const exercise = { id: 3, course: { id: 4 }, problemStatement: problemstatement } as ProgrammingExercise; const loadInitialResultStub = stub(comp, 'loadInitialResult').returns(of(result)); const updateMarkdownStub = stub(comp, 'updateMarkdown'); comp.participation = participation; @@ -259,8 +260,8 @@ describe('ProgrammingExerciseInstructionComponent', () => { it('should still render the instructions if fetching the latest result fails', () => { const participation = { id: 2 } as Participation; - const problemStatement = 'lorem ipsum'; - const exercise = { id: 3, course: { id: 4 }, problemStatement } as ProgrammingExercise; + const problemstatement = 'lorem ipsum'; + const exercise = { id: 3, course: { id: 4 }, problemStatement: problemstatement } as ProgrammingExercise; const updateMarkdownStub = stub(comp, 'updateMarkdown'); getLatestResultWithFeedbacks.returns(throwError('fatal error')); comp.participation = participation; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-status.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-status.component.spec.ts similarity index 96% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-status.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-status.component.spec.ts index 3f75dc8db887..3c5e35a1d6b9 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-status.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-status.component.spec.ts @@ -8,12 +8,12 @@ import { ArtemisTestModule } from '../../test.module'; import { TranslateModule } from '@ngx-translate/core'; import { By } from '@angular/platform-browser'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { SinonStub, stub } from 'sinon'; import { Result } from 'app/entities/result.model'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { ProgrammingExerciseInstructorStatusComponent } from 'app/exercises/programming/manage/status/programming-exercise-instructor-status.component'; import { ProgrammingExerciseParticipationType } from 'app/entities/programming-exercise-participation.model'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; @@ -28,7 +28,6 @@ describe('ProgrammingExerciseInstructorStatusComponent', () => { let fixture: ComponentFixture; let participationWebsocketService: ParticipationWebsocketService; let subscribeForLatestResultStub: SinonStub; - let addParticipationToListStub: SinonStub; let latestResultSubject: Subject; beforeEach(async(() => { @@ -48,7 +47,6 @@ describe('ProgrammingExerciseInstructorStatusComponent', () => { participationWebsocketService = fixture.debugElement.injector.get(ParticipationWebsocketService); - addParticipationToListStub = stub(participationWebsocketService, 'addParticipation'); subscribeForLatestResultStub = stub(participationWebsocketService, 'subscribeForLatestResultOfParticipation'); latestResultSubject = new Subject(); subscribeForLatestResultStub.returns(latestResultSubject); diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.component.spec.ts index 1084cac09d0b..eed64d301e40 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-instructor-submission-state.component.spec.ts @@ -9,24 +9,24 @@ import { of, Subject } from 'rxjs'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; import { Exercise } from 'app/entities/exercise.model'; import { ExerciseSubmissionState, ProgrammingSubmissionService, ProgrammingSubmissionState } from 'app/exercises/programming/participate/programming-submission.service'; import { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module'; import { ProgrammingExerciseInstructorSubmissionStateComponent } from 'app/exercises/programming/shared/actions/programming-exercise-instructor-submission-state.component'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { BuildRunState, ProgrammingBuildRunService } from 'app/exercises/programming/participate/programming-build-run.service'; -import { MockProgrammingBuildRunService } from '../../mocks/mock-programming-build-run.service'; +import { MockProgrammingBuildRunService } from '../../helpers/mocks/service/mock-programming-build-run.service'; import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; -import { MockFeatureToggleService } from '../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; chai.use(sinonChai); const expect = chai.expect; -describe('ProgrammingExerciseInstructorSubmissionState', () => { +describe('ProgrammingExerciseInstructorSubmissionStateComponent', () => { let comp: ProgrammingExerciseInstructorSubmissionStateComponent; let fixture: ComponentFixture; let debugElement: DebugElement; @@ -36,6 +36,7 @@ describe('ProgrammingExerciseInstructorSubmissionState', () => { let getExerciseSubmissionStateStub: SinonStub; let getExerciseSubmissionStateSubject: Subject; + // eslint-disable-next-line @typescript-eslint/no-unused-vars let getBuildRunStateStub: SinonStub; let getBuildRunStateSubject: Subject; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-manage-test-cases.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-manage-test-cases.component.spec.ts similarity index 94% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-manage-test-cases.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-manage-test-cases.component.spec.ts index 03ab8aa2995d..7b2eb9e445cc 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-manage-test-cases.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-manage-test-cases.component.spec.ts @@ -13,32 +13,32 @@ import { AlertService } from 'app/core/alert/alert.service'; import * as chai from 'chai'; import { ArtemisTestModule } from '../../test.module'; import { TranslateModule } from '@ngx-translate/core'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockProgrammingExerciseTestCaseService } from '../../mocks/mock-programming-exercise-test-case.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockProgrammingExerciseTestCaseService } from '../../helpers/mocks/service/mock-programming-exercise-test-case.service'; import { ProgrammingExerciseTestCase } from 'app/entities/programming-exercise-test-case.model'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ArtemisProgrammingExerciseTestCaseModule } from 'app/exercises/programming/manage/test-cases/programming-exercise-test-case.module'; -import { expectElementToBeDisabled, expectElementToBeEnabled, getElement } from '../../utils/general.utils'; +import { expectElementToBeDisabled, expectElementToBeEnabled, getElement } from '../../helpers/utils/general.utils'; import { ProgrammingExerciseWebsocketService } from 'app/exercises/programming/manage/services/programming-exercise-websocket.service'; -import { MockProgrammingExerciseWebsocketService } from '../../mocks/mock-programming-exercise-websocket.service'; +import { MockProgrammingExerciseWebsocketService } from '../../helpers/mocks/service/mock-programming-exercise-websocket.service'; import { ProgrammingBuildRunService } from 'app/exercises/programming/participate/programming-build-run.service'; -import { MockProgrammingBuildRunService } from '../../mocks/mock-programming-build-run.service'; +import { MockProgrammingBuildRunService } from '../../helpers/mocks/service/mock-programming-build-run.service'; import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; -import { MockFeatureToggleService } from '../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service'; import { EditableField, ProgrammingExerciseManageTestCasesComponent } from 'app/exercises/programming/manage/test-cases/programming-exercise-manage-test-cases.component'; import { ProgrammingExerciseService, ProgrammingExerciseTestCaseStateDTO } from 'app/exercises/programming/manage/services/programming-exercise.service'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { ProgrammingExerciseTestCaseService } from 'app/exercises/programming/manage/services/programming-exercise-test-case.service'; -import { MockActivatedRoute } from '../../mocks/mock-activated.route'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; -import { MockProgrammingExerciseService } from '../../mocks/mock-programming-exercise.service'; +import { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; +import { MockProgrammingExerciseService } from '../../helpers/mocks/service/mock-programming-exercise.service'; chai.use(sinonChai); const expect = chai.expect; // TODO: Since the update to v.16 all tests for the ngx-swimlane table need to add a 0 tick to avoid the ViewDestroyedError. // The issue is a manual call to changeDetector.detectChanges that is triggered on a timeout. -describe('ProgrammingExerciseManageTestCases', () => { +describe('ProgrammingExerciseManageTestCasesComponent', () => { let comp: ProgrammingExerciseManageTestCasesComponent; let fixture: ComponentFixture; let debugElement: DebugElement; @@ -62,7 +62,6 @@ describe('ProgrammingExerciseManageTestCases', () => { const tableEditingInput = '.table-editable-field__input'; const rowClass = 'datatable-body-row'; const saveTestCasesButton = '#save-test-cases-button'; - const resetWeightsButton = '#reset-weights-button'; const triggerSubmissionRunButton = '#trigger-all-button > button'; const testCasesNoUnsavedChanges = '#test-case-status-no-unsaved-changes'; const testCasesUnsavedChanges = '#test-case-status-unsaved-changes'; @@ -97,10 +96,6 @@ describe('ProgrammingExerciseManageTestCases', () => { return getElement(debugElement, saveTestCasesButton); }; - const getResetButton = () => { - return getElement(debugElement, resetWeightsButton); - }; - const getTriggerButton = () => { return getElement(debugElement, triggerSubmissionRunButton); }; @@ -133,7 +128,7 @@ describe('ProgrammingExerciseManageTestCases', () => { { provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, { provide: CookieService, useClass: MockCookieService }, - { provide: ActivatedRoute, useClass: MockActivatedRoute }, + { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects }, { provide: FeatureToggleService, useClass: MockFeatureToggleService }, ], }) @@ -160,7 +155,7 @@ describe('ProgrammingExerciseManageTestCases', () => { routeSubject = new Subject(); // @ts-ignore - (route as MockActivatedRoute).setSubject(routeSubject); + (route as MockActivatedRouteWithSubjects).setSubject(routeSubject); getExerciseTestCaseStateSubject = new Subject(); testCasesChangedSubject = new Subject(); @@ -343,8 +338,6 @@ describe('ProgrammingExerciseManageTestCases', () => { routeSubject.next({ exerciseId }); getExerciseTestCaseStateSubject.next(getExerciseTestCasteStateDTO(true, true, false, null)); - const orderedTests = _sortBy(testCases1, 'testName'); - (testCaseService as any).next(testCases1); fixture.detectChanges(); diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.component.spec.ts index ce87d62da0a2..09fcb2432c72 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-test-schedule-picker.component.spec.ts @@ -2,7 +2,6 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import * as moment from 'moment'; import { ComponentFixture, TestBed } from '@angular/core/testing'; -import { DebugElement } from '@angular/core'; import { TranslateModule } from '@ngx-translate/core'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisSharedModule } from 'app/shared/shared.module'; @@ -18,7 +17,6 @@ const expect = chai.expect; describe('ProgrammingExerciseTestSchedulePickerComponent', () => { let comp: ProgrammingExerciseLifecycleComponent; let fixture: ComponentFixture; - let debugElement: DebugElement; const nextDueDate = moment().add(5, 'days'); const afterDueDate = moment().add(7, 'days'); @@ -34,7 +32,6 @@ describe('ProgrammingExerciseTestSchedulePickerComponent', () => { .then(() => { fixture = TestBed.createComponent(ProgrammingExerciseLifecycleComponent); comp = fixture.componentInstance; - debugElement = fixture.debugElement; }); }); diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-trigger-build-button.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-trigger-build-button.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/programming-exercise/programming-exercise-trigger-build-button.spec.ts rename to src/test/javascript/spec/component/programming-exercise/programming-exercise-trigger-build-button.component.spec.ts index b5d36a7d7adf..745ab5569128 100644 --- a/src/test/javascript/spec/component/programming-exercise/programming-exercise-trigger-build-button.spec.ts +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-trigger-build-button.component.spec.ts @@ -12,15 +12,15 @@ import { of, Subject } from 'rxjs'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; import { Result } from 'app/entities/result.model'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { Exercise } from 'app/entities/exercise.model'; import { ProgrammingSubmissionService, ProgrammingSubmissionState, ProgrammingSubmissionStateObj } from 'app/exercises/programming/participate/programming-submission.service'; import { ArtemisProgrammingExerciseActionsModule } from 'app/exercises/programming/shared/actions/programming-exercise-actions.module'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { InitializationState } from 'app/entities/participation/participation.model'; import { ProgrammingExerciseStudentTriggerBuildButtonComponent } from 'app/exercises/programming/shared/actions/programming-exercise-student-trigger-build-button.component'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts new file mode 100644 index 000000000000..38659ea592aa --- /dev/null +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise-update.component.spec.ts @@ -0,0 +1,71 @@ +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; +import * as moment from 'moment'; + +import { ArtemisTestModule } from '../../test.module'; +import { ProgrammingExerciseUpdateComponent } from 'app/exercises/programming/manage/update/programming-exercise-update.component'; +import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; +import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { TranslateService } from '@ngx-translate/core'; +import { Course } from 'app/entities/course.model'; + +describe('ProgrammingExercise Management Update Component', () => { + let comp: ProgrammingExerciseUpdateComponent; + let fixture: ComponentFixture; + let service: ProgrammingExerciseService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ProgrammingExerciseUpdateComponent], + providers: [ + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }) + .overrideTemplate(ProgrammingExerciseUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ProgrammingExerciseUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(ProgrammingExerciseService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new ProgrammingExercise(new Course()); + entity.id = 123; + entity.releaseDate = moment(); // We will get a warning if we do not set a release date + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.programmingExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity, {}); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new ProgrammingExercise(); + entity.releaseDate = moment(); // We will get a warning if we do not set a release date + spyOn(service, 'automaticSetup').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.programmingExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.automaticSetup).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); +}); diff --git a/src/test/javascript/spec/component/programming-exercise/programming-exercise.component.spec.ts b/src/test/javascript/spec/component/programming-exercise/programming-exercise.component.spec.ts new file mode 100644 index 000000000000..6caee6efecfb --- /dev/null +++ b/src/test/javascript/spec/component/programming-exercise/programming-exercise.component.spec.ts @@ -0,0 +1,72 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { ProgrammingExerciseComponent } from 'app/exercises/programming/manage/programming-exercise.component'; +import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { TranslateService } from '@ngx-translate/core'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; +import { Course } from 'app/entities/course.model'; +import { OrionConnectorService } from 'app/shared/orion/orion-connector.service'; +import { MockOrionConnectorService } from '../../helpers/mocks/service/mock-orion-connector.service'; +import { CourseExerciseService } from 'app/course/manage/course-management.service'; +import { MockCourseExerciseService } from '../../helpers/mocks/service/mock-course-exercise.service'; + +describe('ProgrammingExercise Management Component', () => { + const course = { id: 123 } as Course; + const programmingExercise = new ProgrammingExercise(course); + programmingExercise.id = 456; + + let comp: ProgrammingExerciseComponent; + let fixture: ComponentFixture; + let service: CourseExerciseService; + + const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [ProgrammingExerciseComponent], + providers: [ + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + { provide: ActivatedRoute, useValue: route }, + { provide: OrionConnectorService, useClass: MockOrionConnectorService }, + { provide: CourseExerciseService, useClass: MockCourseExerciseService }, + ], + }) + .overrideTemplate(ProgrammingExerciseComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(ProgrammingExerciseComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(CourseExerciseService); + }); + + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'findAllProgrammingExercisesForCourse').and.returnValue( + of( + new HttpResponse({ + body: [programmingExercise], + headers, + }), + ), + ); + + // WHEN + comp.course = course; + fixture.detectChanges(); + comp.ngOnInit(); + + // THEN + expect(service.findAllProgrammingExercisesForCourse).toHaveBeenCalled(); + expect(comp.programmingExercises[0]).toEqual(jasmine.objectContaining({ id: programmingExercise.id })); + }); +}); diff --git a/src/test/javascript/spec/component/quiz-exercise/quiz-exercise-detail.component.spec.ts b/src/test/javascript/spec/component/quiz-exercise/quiz-exercise-detail.component.spec.ts new file mode 100644 index 000000000000..3767741a9df9 --- /dev/null +++ b/src/test/javascript/spec/component/quiz-exercise/quiz-exercise-detail.component.spec.ts @@ -0,0 +1,75 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { QuizExerciseDetailComponent } from 'app/exercises/quiz/manage/quiz-exercise-detail.component'; +import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; +import { Course } from 'app/entities/course.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { TranslateService } from '@ngx-translate/core'; +import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; + +describe('QuizExercise Management Detail Component', () => { + let comp: QuizExerciseDetailComponent; + let courseManagementService: CourseManagementService; + let quizExerciseService: QuizExerciseService; + let fixture: ComponentFixture; + + const course: Course = { id: 123 } as Course; + const quizExercise = new QuizExercise(course); + quizExercise.id = 456; + + const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id, exerciseId: quizExercise.id }) } } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [QuizExerciseDetailComponent], + providers: [ + { provide: ActivatedRoute, useValue: route }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }) + .overrideTemplate(QuizExerciseDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(QuizExerciseDetailComponent); + comp = fixture.componentInstance; + courseManagementService = fixture.debugElement.injector.get(CourseManagementService); + quizExerciseService = fixture.debugElement.injector.get(QuizExerciseService); + }); + + describe('OnInit', () => { + it('Should call courseExerciseService.find and quizExerciseService.find', () => { + // GIVEN + spyOn(courseManagementService, 'find').and.returnValue( + of( + new HttpResponse({ + body: course, + }), + ), + ); + spyOn(quizExerciseService, 'find').and.returnValue( + of( + new HttpResponse({ + body: quizExercise, + }), + ), + ); + + // WHEN + comp.course = course; + comp.ngOnInit(); + + // THEN + expect(courseManagementService.find).toHaveBeenCalled(); + expect(quizExerciseService.find).toHaveBeenCalled(); + }); + }); +}); diff --git a/src/test/javascript/spec/component/quiz-exercise/quiz-exercise.component.spec.ts b/src/test/javascript/spec/component/quiz-exercise/quiz-exercise.component.spec.ts new file mode 100644 index 000000000000..f57c893b43b1 --- /dev/null +++ b/src/test/javascript/spec/component/quiz-exercise/quiz-exercise.component.spec.ts @@ -0,0 +1,65 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { TranslateService } from '@ngx-translate/core'; + +import { ArtemisTestModule } from '../../test.module'; +import { QuizExerciseComponent } from 'app/exercises/quiz/manage/quiz-exercise.component'; +import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; +import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { Course } from 'app/entities/course.model'; + +describe('QuizExercise Management Component', () => { + let comp: QuizExerciseComponent; + let fixture: ComponentFixture; + let service: QuizExerciseService; + + const course = { id: 123 } as Course; + const quizExercise = new QuizExercise(course); + quizExercise.id = 456; + const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [QuizExerciseComponent], + providers: [ + { provide: ActivatedRoute, useValue: route }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }) + .overrideTemplate(QuizExerciseComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(QuizExerciseComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(QuizExerciseService); + }); + + it('Should call loadExercises on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'findForCourse').and.returnValue( + of( + new HttpResponse({ + body: [quizExercise], + headers, + }), + ), + ); + + // WHEN + comp.course = course; + comp.ngOnInit(); + + // THEN + expect(service.findForCourse).toHaveBeenCalled(); + expect(comp.quizExercises[0]).toEqual(quizExercise); + }); +}); diff --git a/src/test/javascript/spec/component/shared/alert-error.component.spec.ts b/src/test/javascript/spec/component/shared/alert-error.component.spec.ts new file mode 100644 index 000000000000..e73190c8e2c2 --- /dev/null +++ b/src/test/javascript/spec/component/shared/alert-error.component.spec.ts @@ -0,0 +1,134 @@ +import { async, ComponentFixture, TestBed } from '@angular/core/testing'; +import { HttpErrorResponse, HttpHeaders } from '@angular/common/http'; +import { JhiEventManager } from 'ng-jhipster'; +import { TranslateModule } from '@ngx-translate/core'; + +import { ArtemisTestModule } from '../../test.module'; +import { AlertErrorComponent } from 'app/shared/alert/alert-error.component'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; +import { AlertService } from 'app/core/alert/alert.service'; + +describe('Alert Error Component', () => { + let comp: AlertErrorComponent; + let fixture: ComponentFixture; + let eventManager: JhiEventManager; + + beforeEach(async(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule, TranslateModule.forRoot()], + declarations: [AlertErrorComponent], + providers: [ + JhiEventManager, + { + provide: AlertService, + useClass: MockAlertService, + }, + ], + }) + .overrideTemplate(AlertErrorComponent, '') + .compileComponents(); + })); + + beforeEach(() => { + fixture = TestBed.createComponent(AlertErrorComponent); + comp = fixture.componentInstance; + eventManager = fixture.debugElement.injector.get(JhiEventManager); + }); + + describe('Error Handling', () => { + it('Should display an alert on status 0', () => { + // GIVEN + eventManager.broadcast({ name: 'artemisApp.httpError', content: { status: 0 } }); + // THEN + expect(comp.alerts.length).toBe(1); + expect(comp.alerts[0].msg).toBe('error.server.not.reachable'); + }); + it('Should display an alert on status 404', () => { + // GIVEN + eventManager.broadcast({ name: 'artemisApp.httpError', content: { status: 404 } }); + // THEN + expect(comp.alerts.length).toBe(1); + expect(comp.alerts[0].msg).toBe('error.url.not.found'); + }); + it('Should display an alert on generic error', () => { + // GIVEN + eventManager.broadcast({ name: 'artemisApp.httpError', content: { error: { message: 'Error Message' } } }); + eventManager.broadcast({ name: 'artemisApp.httpError', content: { error: 'Second Error Message' } }); + // THEN + expect(comp.alerts.length).toBe(2); + expect(comp.alerts[0].msg).toBe('Error Message'); + expect(comp.alerts[1].msg).toBe('Second Error Message'); + }); + it('Should display an alert on status 400 for generic error', () => { + // GIVEN + const response = new HttpErrorResponse({ + url: 'http://localhost:8080/api/foos', + headers: new HttpHeaders(), + status: 400, + statusText: 'Bad Request', + error: { + type: 'https://www.jhipster.tech/problem/constraint-violation', + title: 'Bad Request', + status: 400, + path: '/api/foos', + message: 'error.validation', + }, + }); + eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); + // THEN + expect(comp.alerts.length).toBe(1); + expect(comp.alerts[0].msg).toBe('error.validation'); + }); + it('Should display an alert on status 400 for generic error without message', () => { + // GIVEN + const response = new HttpErrorResponse({ + url: 'http://localhost:8080/api/foos', + headers: new HttpHeaders(), + status: 400, + error: 'Bad Request', + }); + eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); + // THEN + expect(comp.alerts.length).toBe(1); + expect(comp.alerts[0].msg).toBe('Bad Request'); + }); + it('Should display an alert on status 400 for invalid parameters', () => { + // GIVEN + const response = new HttpErrorResponse({ + url: 'http://localhost:8080/api/foos', + headers: new HttpHeaders(), + status: 400, + statusText: 'Bad Request', + error: { + type: 'https://www.jhipster.tech/problem/constraint-violation', + title: 'Method argument not valid', + status: 400, + path: '/api/foos', + message: 'error.validation', + fieldErrors: [{ objectName: 'foo', field: 'minField', message: 'Min' }], + }, + }); + eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); + // THEN + expect(comp.alerts.length).toBe(1); + expect(comp.alerts[0].msg).toBe('error.Size'); + }); + it('Should display an alert on status 400 for error headers', () => { + // GIVEN + const response = new HttpErrorResponse({ + url: 'http://localhost:8080/api/foos', + headers: new HttpHeaders().append('app-error', 'Error Message').append('app-params', 'foo'), + status: 400, + statusText: 'Bad Request', + error: { + status: 400, + message: 'error.validation', + }, + }); + eventManager.broadcast({ name: 'artemisApp.httpError', content: response }); + // THEN + expect(comp.alerts.length).toBe(1); + expect(comp.alerts[0].msg).toBe('Error Message'); + }); + }); +}); diff --git a/src/test/javascript/spec/component/shared/button-component.spec.ts b/src/test/javascript/spec/component/shared/button.component.spec.ts similarity index 96% rename from src/test/javascript/spec/component/shared/button-component.spec.ts rename to src/test/javascript/spec/component/shared/button.component.spec.ts index 42c769490390..22d8f2753512 100644 --- a/src/test/javascript/spec/component/shared/button-component.spec.ts +++ b/src/test/javascript/spec/component/shared/button.component.spec.ts @@ -9,9 +9,9 @@ import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { FeatureToggleService } from 'app/shared/feature-toggle/feature-toggle.service'; -import { MockFeatureToggleService } from '../../mocks/mock-feature-toggle-service'; +import { MockFeatureToggleService } from '../../helpers/mocks/service/mock-feature-toggle.service'; import { ButtonComponent } from 'app/shared/components/button.component'; chai.use(sinonChai); diff --git a/src/test/javascript/spec/component/shared/delete-dialog.spec.ts b/src/test/javascript/spec/component/shared/delete-dialog.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/shared/delete-dialog.spec.ts rename to src/test/javascript/spec/component/shared/delete-dialog.component.spec.ts diff --git a/src/test/javascript/spec/component/shared/result-detail.spec.ts b/src/test/javascript/spec/component/shared/result-detail.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/shared/result-detail.spec.ts rename to src/test/javascript/spec/component/shared/result-detail.component.spec.ts diff --git a/src/test/javascript/spec/component/shared/secured-image.spec.ts b/src/test/javascript/spec/component/shared/secured-image.component.spec.ts similarity index 99% rename from src/test/javascript/spec/component/shared/secured-image.spec.ts rename to src/test/javascript/spec/component/shared/secured-image.component.spec.ts index 94879e7fd2ed..2ee8f7d43e9e 100644 --- a/src/test/javascript/spec/component/shared/secured-image.spec.ts +++ b/src/test/javascript/spec/component/shared/secured-image.component.spec.ts @@ -7,8 +7,8 @@ import { SinonStub, stub } from 'sinon'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; -import { MockCacheableImageService } from '../../mocks/mock-cacheable-image.service'; -import { triggerChanges } from '../../utils/general.utils'; +import { MockCacheableImageService } from '../../helpers/mocks/service/mock-cacheable-image.service'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { UpdatingResultComponent } from 'app/shared/result/updating-result.component'; import { CachingStrategy, ImageLoadingStatus, SecuredImageComponent } from 'app/shared/image/secured-image.component'; diff --git a/src/test/javascript/spec/component/shared/updating-result.spec.ts b/src/test/javascript/spec/component/shared/updating-result.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/shared/updating-result.spec.ts rename to src/test/javascript/spec/component/shared/updating-result.component.spec.ts index ad18fe1b1227..b8b6d05b885b 100644 --- a/src/test/javascript/spec/component/shared/updating-result.spec.ts +++ b/src/test/javascript/spec/component/shared/updating-result.component.spec.ts @@ -14,17 +14,17 @@ import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { ProgrammingSubmissionService, ProgrammingSubmissionState } from 'app/exercises/programming/participate/programming-submission.service'; -import { MockProgrammingSubmissionService } from '../../mocks/mock-programming-submission.service'; -import { triggerChanges } from '../../utils/general.utils'; +import { MockProgrammingSubmissionService } from '../../helpers/mocks/service/mock-programming-submission.service'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { Exercise, ExerciseType } from 'app/entities/exercise.model'; import { UpdatingResultComponent } from 'app/shared/result/updating-result.component'; import { ResultComponent } from 'app/shared/result/result.component'; import { CodeEditorFileService } from 'app/exercises/programming/shared/code-editor/service/code-editor-file.service'; import { Result } from 'app/entities/result.model'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/component/student-questions/student-question-answer.service.spec.ts b/src/test/javascript/spec/component/student-questions/student-question-answer.service.spec.ts deleted file mode 100644 index f047094fd611..000000000000 --- a/src/test/javascript/spec/component/student-questions/student-question-answer.service.spec.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { HttpResponse } from '@angular/common/http'; -import * as chai from 'chai'; -import { take } from 'rxjs/operators'; -import { StudentQuestionAnswerService } from 'app/overview/student-questions/student-question-answer.service'; -import { StudentQuestionAnswer } from 'app/entities/student-question-answer.model'; - -const expect = chai.expect; - -describe('Service Tests', () => { - describe('ExerciseHint Service', () => { - let injector: TestBed; - let service: StudentQuestionAnswerService; - let httpMock: HttpTestingController; - let elemDefault: StudentQuestionAnswer; - let expectedResult: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - expectedResult = {} as HttpResponse; - injector = getTestBed(); - service = injector.get(StudentQuestionAnswerService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new StudentQuestionAnswer(); - elemDefault.id = 0; - elemDefault.answerDate = null; - elemDefault.answerText = 'This is a test answer'; - }); - - describe('Service methods', () => { - it('should find a StudentQuestionAnswer', async () => { - const returnedFromService = { ...elemDefault }; - service - .find(123) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - - const req = httpMock.expectOne({ method: 'GET' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(elemDefault); - }); - - it('should create a StudentQuestionAnswer', async () => { - const returnedFromService = { ...elemDefault, id: 0 }; - const expected = { ...returnedFromService }; - service - .create(new StudentQuestionAnswer()) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should update a StudentQuestionAnswer text field', async () => { - const returnedFromService = { ...elemDefault, answerText: 'This is another test answer' }; - const expected = { ...returnedFromService }; - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should update a StudentQuestionAnswer tutorApproved field', async () => { - const returnedFromService = { ...elemDefault, tutorApproved: true }; - const expected = { ...returnedFromService }; - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should delete a StudentQuestionAnswer', async () => { - const rxPromise = service.delete(123).subscribe((resp) => (expectedResult = resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - expect(expectedResult).to.be.true; - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/component/student-questions/student-question.service.spec.ts b/src/test/javascript/spec/component/student-questions/student-question.service.spec.ts deleted file mode 100644 index 95d3bcc53354..000000000000 --- a/src/test/javascript/spec/component/student-questions/student-question.service.spec.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { getTestBed, TestBed } from '@angular/core/testing'; -import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; -import { HttpResponse } from '@angular/common/http'; -import * as chai from 'chai'; -import { take } from 'rxjs/operators'; -import { StudentQuestionService } from 'app/overview/student-questions/student-question.service'; -import { StudentQuestion } from 'app/entities/student-question.model'; - -const expect = chai.expect; - -describe('Service Tests', () => { - describe('ExerciseHint Service', () => { - let injector: TestBed; - let service: StudentQuestionService; - let httpMock: HttpTestingController; - let elemDefault: StudentQuestion; - let expectedResult: any; - - beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - }); - expectedResult = {} as HttpResponse; - injector = getTestBed(); - service = injector.get(StudentQuestionService); - httpMock = injector.get(HttpTestingController); - - elemDefault = new StudentQuestion(); - elemDefault.id = 0; - elemDefault.creationDate = null; - elemDefault.questionText = 'This is a test question'; - }); - - describe('Service methods', () => { - it('should create a StudentQuestion', async () => { - const returnedFromService = { ...elemDefault, id: 0 }; - const expected = { ...returnedFromService }; - service - .create(new StudentQuestion()) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'POST' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should update a StudentQuestion', async () => { - const returnedFromService = { ...elemDefault, questionText: 'This is another test question' }; - - const expected = { ...returnedFromService }; - service - .update(expected) - .pipe(take(1)) - .subscribe((resp) => (expectedResult = resp)); - const req = httpMock.expectOne({ method: 'PUT' }); - req.flush(returnedFromService); - expect(expectedResult.body).to.deep.equal(expected); - }); - - it('should delete a StudentQuestion', async () => { - const rxPromise = service.delete(123).subscribe((resp) => (expectedResult = resp.ok)); - - const req = httpMock.expectOne({ method: 'DELETE' }); - req.flush({ status: 200 }); - expect(expectedResult).to.be.true; - }); - }); - - afterEach(() => { - httpMock.verify(); - }); - }); -}); diff --git a/src/test/javascript/spec/component/student-questions/student-questions.component.spec.ts b/src/test/javascript/spec/component/student-questions/student-questions.component.spec.ts index 0c7eb998eaaa..0ce6678509b3 100644 --- a/src/test/javascript/spec/component/student-questions/student-questions.component.spec.ts +++ b/src/test/javascript/spec/component/student-questions/student-questions.component.spec.ts @@ -3,7 +3,7 @@ import * as sinonChai from 'sinon-chai'; import { ComponentFixture, TestBed } from '@angular/core/testing'; import { TranslateModule } from '@ngx-translate/core'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; import { StudentQuestionsComponent } from 'app/overview/student-questions/student-questions.component'; import { Lecture } from 'app/entities/lecture.model'; import { StudentQuestionAnswer } from 'app/entities/student-question-answer.model'; diff --git a/src/test/javascript/spec/component/table/table-editable-checkbox.spec.ts b/src/test/javascript/spec/component/table/table-editable-checkbox.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/table/table-editable-checkbox.spec.ts rename to src/test/javascript/spec/component/table/table-editable-checkbox.component.spec.ts diff --git a/src/test/javascript/spec/component/table/table-editable-field.spec.ts b/src/test/javascript/spec/component/table/table-editable-field.component.spec.ts similarity index 98% rename from src/test/javascript/spec/component/table/table-editable-field.spec.ts rename to src/test/javascript/spec/component/table/table-editable-field.component.spec.ts index 9eeb91eb0efe..67d422a797c8 100644 --- a/src/test/javascript/spec/component/table/table-editable-field.spec.ts +++ b/src/test/javascript/spec/component/table/table-editable-field.component.spec.ts @@ -5,7 +5,7 @@ import { DebugElement } from '@angular/core'; import * as chai from 'chai'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisTableModule } from 'app/shared/table/table.module'; -import { triggerChanges } from '../../utils/general.utils'; +import { triggerChanges } from '../../helpers/utils/general.utils'; import { TableEditableFieldComponent } from 'app/shared/table/table-editable-field.component'; const expect = chai.expect; diff --git a/src/test/javascript/spec/component/team/team-update-dialog.spec.ts b/src/test/javascript/spec/component/team/team-update-dialog.component.spec.ts similarity index 96% rename from src/test/javascript/spec/component/team/team-update-dialog.spec.ts rename to src/test/javascript/spec/component/team/team-update-dialog.component.spec.ts index 847eec97bb8a..2890c50b5973 100644 --- a/src/test/javascript/spec/component/team/team-update-dialog.spec.ts +++ b/src/test/javascript/spec/component/team/team-update-dialog.component.spec.ts @@ -11,13 +11,13 @@ import { FormsModule } from '@angular/forms'; import { NgbActiveModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'; import * as sinon from 'sinon'; import { AlertService } from 'app/core/alert/alert.service'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module'; import { ArtemisTeamModule } from 'app/exercises/shared/team/team.module'; -import { mockEmptyTeam, mockExercise, mockNonTeamStudents, mockTeam, MockTeamService, mockTeamStudents } from '../../mocks/mock-team.service'; +import { mockEmptyTeam, mockExercise, mockNonTeamStudents, mockTeam, MockTeamService, mockTeamStudents } from '../../helpers/mocks/service/mock-team.service'; import { TeamService } from 'app/exercises/shared/team/team.service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; chai.use(sinonChai); @@ -26,7 +26,6 @@ const expect = chai.expect; describe('TeamUpdateDialogComponent', () => { let comp: TeamUpdateDialogComponent; let fixture: ComponentFixture; - let service: TeamService; let debugElement: DebugElement; let ngbActiveModal: NgbActiveModal; @@ -47,7 +46,6 @@ describe('TeamUpdateDialogComponent', () => { fixture = TestBed.createComponent(TeamUpdateDialogComponent); comp = fixture.componentInstance; debugElement = fixture.debugElement; - service = debugElement.injector.get(TeamService); ngbActiveModal = TestBed.inject(NgbActiveModal); }); }); diff --git a/src/test/javascript/spec/component/team/teams.spec.ts b/src/test/javascript/spec/component/team/teams.component.spec.ts similarity index 81% rename from src/test/javascript/spec/component/team/teams.spec.ts rename to src/test/javascript/spec/component/team/teams.component.spec.ts index c36c17fa2ec1..c56e132ec4f0 100644 --- a/src/test/javascript/spec/component/team/teams.spec.ts +++ b/src/test/javascript/spec/component/team/teams.component.spec.ts @@ -7,9 +7,9 @@ import { ArtemisTestModule } from '../../test.module'; import { By } from '@angular/platform-browser'; import { JhiEventManager, NgJhipsterModule } from 'ng-jhipster'; import { FormsModule } from '@angular/forms'; -import { NgbActiveModal, NgbModule } from '@ng-bootstrap/ng-bootstrap'; +import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AlertService } from 'app/core/alert/alert.service'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module'; import { ArtemisTeamModule } from 'app/exercises/shared/team/team.module'; @@ -21,20 +21,19 @@ import { DifferencePipe } from 'ngx-moment'; import { SortByPipe } from 'app/shared/pipes/sort-by.pipe'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { CookieService } from 'ngx-cookie-service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockCookieService } from '../../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../../helpers/mocks/service/mock-cookie.service'; import { ActivatedRoute } from '@angular/router'; import { of } from 'rxjs'; -import { mockTeams, MockTeamService } from '../../mocks/mock-team.service'; -import { MockExerciseService } from '../../mocks/mock-exercise.service'; +import { mockTeams, MockTeamService } from '../../helpers/mocks/service/mock-team.service'; +import { MockExerciseService } from '../../helpers/mocks/service/mock-exercise.service'; import { teamRoute } from 'app/exercises/shared/team/team.route.ts'; import { RouterTestingModule } from '@angular/router/testing'; import { Router } from '@angular/router'; -import { Location } from '@angular/common'; import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; -import { MockParticipationService } from '../../mocks/mock-participation.service'; +import { MockParticipationService } from '../../helpers/mocks/service/mock-participation.service'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../../mocks/mock-account.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; chai.use(sinonChai); const expect = chai.expect; @@ -42,11 +41,8 @@ const expect = chai.expect; describe('TeamsComponent', () => { let comp: TeamsComponent; let fixture: ComponentFixture; - let service: TeamService; let debugElement: DebugElement; let router: Router; - let location: Location; - let ngbActiveModal: NgbActiveModal; const route = ({ params: of({ exerciseId: 1 }), @@ -88,9 +84,6 @@ describe('TeamsComponent', () => { comp = fixture.componentInstance; debugElement = fixture.debugElement; router = debugElement.injector.get(Router); - location = debugElement.injector.get(Location); - service = debugElement.injector.get(TeamService); - ngbActiveModal = TestBed.inject(NgbActiveModal); router.initialNavigation(); }); }); diff --git a/src/test/javascript/spec/component/text-editor/text-editor.spec.ts b/src/test/javascript/spec/component/text-editor/text-editor.component.spec.ts similarity index 97% rename from src/test/javascript/spec/component/text-editor/text-editor.spec.ts rename to src/test/javascript/spec/component/text-editor/text-editor.component.spec.ts index 59d5cdb4b11e..e46fb3202cd2 100644 --- a/src/test/javascript/spec/component/text-editor/text-editor.spec.ts +++ b/src/test/javascript/spec/component/text-editor/text-editor.component.spec.ts @@ -6,7 +6,7 @@ import { ComponentFixture, fakeAsync, TestBed, tick, flush } from '@angular/core import { AlertService } from 'app/core/alert/alert.service'; import { ArtemisTestModule } from '../../test.module'; import { TranslateModule } from '@ngx-translate/core'; -import { MockTextEditorService } from '../../mocks/mock-text-editor.service'; +import { MockTextEditorService } from '../../helpers/mocks/service/mock-text-editor.service'; import { SinonStub, stub } from 'sinon'; import * as sinonChai from 'sinon-chai'; import { TextEditorService } from 'app/exercises/text/participate/text-editor.service'; @@ -14,7 +14,7 @@ import { BehaviorSubject } from 'rxjs'; import { ArtemisSharedModule } from 'app/shared/shared.module'; import { RouterTestingModule } from '@angular/router/testing'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { MockComponent } from 'ng-mocks'; import { TextResultComponent } from 'app/exercises/text/participate/text-result/text-result.component'; import { ComplaintInteractionsComponent } from 'app/complaints/complaint-interactions.component'; @@ -34,7 +34,7 @@ import { ArtemisHeaderExercisePageWithDetailsModule } from 'app/exercises/shared chai.use(sinonChai); const expect = chai.expect; -describe('TableEditableFieldComponent', () => { +describe('TextEditorComponent', () => { let comp: TextEditorComponent; let fixture: ComponentFixture; let debugElement: DebugElement; diff --git a/src/test/javascript/spec/component/text-exercise/text-exercise-detail.component.spec.ts b/src/test/javascript/spec/component/text-exercise/text-exercise-detail.component.spec.ts new file mode 100644 index 000000000000..cc8aa76e3cdc --- /dev/null +++ b/src/test/javascript/spec/component/text-exercise/text-exercise-detail.component.spec.ts @@ -0,0 +1,51 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { ActivatedRoute } from '@angular/router'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { ArtemisTestModule } from '../../test.module'; +import { TextExerciseDetailComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-detail.component'; +import { Course } from 'app/entities/course.model'; +import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; + +describe('TextExercise Management Detail Component', () => { + let comp: TextExerciseDetailComponent; + let fixture: ComponentFixture; + let service: TextExerciseService; + const course: Course = { id: 123 } as Course; + const route = ({ params: of({ courseId: course.id }) } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [TextExerciseDetailComponent], + providers: [{ provide: ActivatedRoute, useValue: route }], + }) + .overrideTemplate(TextExerciseDetailComponent, '') + .compileComponents(); + fixture = TestBed.createComponent(TextExerciseDetailComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(TextExerciseService); + }); + + describe('OnInit', () => { + it('Should call load all on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(service, 'find').and.returnValue( + of( + new HttpResponse({ + body: course, + headers, + }), + ), + ); + // WHEN + fixture.detectChanges(); + comp.ngOnInit(); + + // THEN + expect(service.find).toHaveBeenCalled(); + expect(comp.textExercise).toEqual(jasmine.objectContaining({ id: course.id })); + }); + }); +}); diff --git a/src/test/javascript/spec/component/text-exercise/text-exercise-update.component.spec.ts b/src/test/javascript/spec/component/text-exercise/text-exercise-update.component.spec.ts new file mode 100644 index 000000000000..1f07590eb749 --- /dev/null +++ b/src/test/javascript/spec/component/text-exercise/text-exercise-update.component.spec.ts @@ -0,0 +1,64 @@ +import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; +import { HttpResponse } from '@angular/common/http'; +import { of } from 'rxjs'; + +import { ArtemisTestModule } from '../../test.module'; +import { TextExerciseUpdateComponent } from 'app/exercises/text/manage/text-exercise/text-exercise-update.component'; +import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; +import { TextExercise } from 'app/entities/text-exercise.model'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; + +describe('TextExercise Management Update Component', () => { + let comp: TextExerciseUpdateComponent; + let fixture: ComponentFixture; + let service: TextExerciseService; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + providers: [ + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + ], + declarations: [TextExerciseUpdateComponent], + }) + .overrideTemplate(TextExerciseUpdateComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(TextExerciseUpdateComponent); + comp = fixture.componentInstance; + service = fixture.debugElement.injector.get(TextExerciseService); + }); + + describe('save', () => { + it('Should call update service on save for existing entity', fakeAsync(() => { + // GIVEN + const entity = new TextExercise(); + entity.id = 123; + spyOn(service, 'update').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.textExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.update).toHaveBeenCalledWith(entity, {}); + expect(comp.isSaving).toEqual(false); + })); + + it('Should call create service on save for new entity', fakeAsync(() => { + // GIVEN + const entity = new TextExercise(); + spyOn(service, 'create').and.returnValue(of(new HttpResponse({ body: entity }))); + comp.textExercise = entity; + // WHEN + comp.save(); + tick(); // simulate async + + // THEN + expect(service.create).toHaveBeenCalledWith(entity); + expect(comp.isSaving).toEqual(false); + })); + }); +}); diff --git a/src/test/javascript/spec/component/text-exercise/text-exercise.component.spec.ts b/src/test/javascript/spec/component/text-exercise/text-exercise.component.spec.ts new file mode 100644 index 000000000000..58836841e900 --- /dev/null +++ b/src/test/javascript/spec/component/text-exercise/text-exercise.component.spec.ts @@ -0,0 +1,63 @@ +import { ComponentFixture, TestBed } from '@angular/core/testing'; +import { of } from 'rxjs'; +import { HttpHeaders, HttpResponse } from '@angular/common/http'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { TranslateService } from '@ngx-translate/core'; +import { ActivatedRoute, convertToParamMap } from '@angular/router'; + +import { ArtemisTestModule } from '../../test.module'; +import { TextExerciseComponent } from 'app/exercises/text/manage/text-exercise/text-exercise.component'; +import { TextExercise } from 'app/entities/text-exercise.model'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockTranslateService } from '../../helpers/mocks/service/mock-translate.service'; +import { CourseExerciseService } from 'app/course/manage/course-management.service'; +import { Course } from 'app/entities/course.model'; + +describe('TextExercise Management Component', () => { + let comp: TextExerciseComponent; + let fixture: ComponentFixture; + let courseExerciseService: CourseExerciseService; + + const course = { id: 123 } as Course; + const textExercise: TextExercise = { id: 456 } as TextExercise; + const route = ({ snapshot: { paramMap: convertToParamMap({ courseId: course.id }) } } as any) as ActivatedRoute; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule], + declarations: [TextExerciseComponent], + providers: [ + { provide: ActivatedRoute, useValue: route }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }) + .overrideTemplate(TextExerciseComponent, '') + .compileComponents(); + + fixture = TestBed.createComponent(TextExerciseComponent); + comp = fixture.componentInstance; + courseExerciseService = fixture.debugElement.injector.get(CourseExerciseService); + }); + + it('Should call loadExercises on init', () => { + // GIVEN + const headers = new HttpHeaders().append('link', 'link;link'); + spyOn(courseExerciseService, 'findAllTextExercisesForCourse').and.returnValue( + of( + new HttpResponse({ + body: [textExercise], + headers, + }), + ), + ); + + // WHEN + comp.course = course; + comp.ngOnInit(); + + // THEN + expect(courseExerciseService.findAllTextExercisesForCourse).toHaveBeenCalled(); + }); +}); diff --git a/src/test/javascript/spec/component/text-submission-assessment/text-assessment-area.spec.ts b/src/test/javascript/spec/component/text-submission-assessment/text-assessment-area.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/text-submission-assessment/text-assessment-area.spec.ts rename to src/test/javascript/spec/component/text-submission-assessment/text-assessment-area.component.spec.ts diff --git a/src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.spec.ts b/src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.component.spec.ts similarity index 97% rename from src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.spec.ts rename to src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.component.spec.ts index 11abff2c4a54..453ea82807da 100644 --- a/src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.spec.ts +++ b/src/test/javascript/spec/component/text-submission-assessment/text-submission-assessment.component.spec.ts @@ -24,6 +24,7 @@ import moment = require('moment'); import { StudentParticipation } from 'app/entities/participation/student-participation.model'; import { ActivatedRoute } from '@angular/router'; import { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.module'; +import { Course } from 'app/entities/course.model'; describe('TextSubmissionAssessmentComponent', () => { let component: TextSubmissionAssessmentComponent; @@ -35,6 +36,7 @@ describe('TextSubmissionAssessmentComponent', () => { type: ExerciseType.TEXT, assessmentType: AssessmentType.MANUAL, problemStatement: '', + course: { id: 123, isAtLeastInstructor: true } as Course, } as TextExercise; const participation: StudentParticipation = ({ type: ParticipationType.STUDENT, diff --git a/src/test/javascript/spec/component/text-submission-assessment/textblock-assessment-card.spec.ts b/src/test/javascript/spec/component/text-submission-assessment/textblock-assessment-card.component.spec.ts similarity index 100% rename from src/test/javascript/spec/component/text-submission-assessment/textblock-assessment-card.spec.ts rename to src/test/javascript/spec/component/text-submission-assessment/textblock-assessment-card.component.spec.ts diff --git a/src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.spec.ts b/src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.component.spec.ts similarity index 98% rename from src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.spec.ts rename to src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.component.spec.ts index a96d524a9cc6..cb3c3f9745f0 100644 --- a/src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.spec.ts +++ b/src/test/javascript/spec/component/text-submission-assessment/textblock-feedback-editor.component.spec.ts @@ -8,7 +8,6 @@ import { ArtemisConfirmIconModule } from 'app/shared/confirm-icon/confirm-icon.m import { TranslateModule } from '@ngx-translate/core'; import { MockComponent } from 'ng-mocks'; import { FaIconComponent } from '@fortawesome/angular-fontawesome'; -import { By } from '@angular/platform-browser'; describe('TextblockFeedbackEditorComponent', () => { let component: TextblockFeedbackEditorComponent; diff --git a/src/test/javascript/spec/component/tutor-dashboard/tutor-exercise-dashboard.spec.ts b/src/test/javascript/spec/component/tutor-dashboard/tutor-exercise-dashboard.component.spec.ts similarity index 95% rename from src/test/javascript/spec/component/tutor-dashboard/tutor-exercise-dashboard.spec.ts rename to src/test/javascript/spec/component/tutor-dashboard/tutor-exercise-dashboard.component.spec.ts index 7ff50d85cb5d..2f33a23c994c 100644 --- a/src/test/javascript/spec/component/tutor-dashboard/tutor-exercise-dashboard.spec.ts +++ b/src/test/javascript/spec/component/tutor-dashboard/tutor-exercise-dashboard.component.spec.ts @@ -4,14 +4,14 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { SinonStub, stub } from 'sinon'; import { ArtemisTestModule } from '../../test.module'; -import { MockActivatedRoute } from '../../mocks/mock-activated.route'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { MockComponent } from 'ng-mocks'; import { ArtemisSharedModule } from 'app/shared/shared.module'; -import { MockAlertService } from '../../helpers/mock-alert.service'; +import { MockAlertService } from '../../helpers/mocks/service/mock-alert.service'; import { AlertService } from 'app/core/alert/alert.service'; import { ActivatedRoute, Router, RouterModule } from '@angular/router'; -import { MockRouter } from '../../mocks/mock-router.service'; +import { MockRouter } from '../../helpers/mocks/mock-router'; import { of, throwError } from 'rxjs'; import { HttpErrorResponse } from '@angular/common/http'; import { SidePanelComponent } from 'app/shared/side-panel/side-panel.component'; @@ -84,7 +84,7 @@ describe('TutorExerciseDashboardComponent', () => { JhiLanguageHelper, DeviceDetectorService, { provide: AlertService, useClass: MockAlertService }, - { provide: ActivatedRoute, useClass: MockActivatedRoute }, + { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects }, { provide: Router, useClass: MockRouter }, { provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, diff --git a/src/test/javascript/spec/component/tutor-dashboard/tutor-participation-graph.component.spec.ts b/src/test/javascript/spec/component/tutor-dashboard/tutor-participation-graph.component.spec.ts index cb9a362f389b..baee7d3bed7e 100644 --- a/src/test/javascript/spec/component/tutor-dashboard/tutor-participation-graph.component.spec.ts +++ b/src/test/javascript/spec/component/tutor-dashboard/tutor-participation-graph.component.spec.ts @@ -4,7 +4,7 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { ArtemisTestModule } from '../../test.module'; import { ArtemisSharedModule } from 'app/shared/shared.module'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { TranslateModule } from '@ngx-translate/core'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { TutorParticipationGraphComponent } from 'app/shared/dashboards/tutor-participation-graph/tutor-participation-graph.component'; diff --git a/src/test/javascript/spec/component/programming-exercise/build-plan-link.directive.spec.ts b/src/test/javascript/spec/directive/build-plan-link.directive.spec.ts similarity index 88% rename from src/test/javascript/spec/component/programming-exercise/build-plan-link.directive.spec.ts rename to src/test/javascript/spec/directive/build-plan-link.directive.spec.ts index c9e147367f7a..52c5fe0bb4bb 100644 --- a/src/test/javascript/spec/component/programming-exercise/build-plan-link.directive.spec.ts +++ b/src/test/javascript/spec/directive/build-plan-link.directive.spec.ts @@ -3,10 +3,10 @@ import * as sinonChai from 'sinon-chai'; import { SinonStub, stub } from 'sinon'; import { Component, DebugElement } from '@angular/core'; import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; -import { ArtemisTestModule } from '../../test.module'; +import { ArtemisTestModule } from '../test.module'; import { ProgrammingExerciseUtilsModule } from 'app/exercises/programming/shared/utils/programming-exercise-utils.module'; import { ProfileService } from 'app/shared/layouts/profiles/profile.service'; -import { MockProfileService } from '../../mocks/mock-profile.service'; +import { MockProfileService } from '../helpers/mocks/service/mock-profile.service'; import { BehaviorSubject } from 'rxjs'; import { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model'; import { By } from '@angular/platform-browser'; @@ -24,13 +24,11 @@ class TestComponent { } describe('BuildPlanLinkDirective', () => { - let comp: TestComponent; let fixture: ComponentFixture; let debugElement: DebugElement; let profileService: ProfileService; let getProfileInfoStub: SinonStub; let profileInfoSubject: BehaviorSubject; - let correctBuildPlan: string; const profileInfo = { buildPlanURLTemplate: 'https://some.url.com/plans/{buildPlanId}/path/{projectKey}' } as ProfileInfo; @@ -43,7 +41,6 @@ describe('BuildPlanLinkDirective', () => { .compileComponents() .then(() => { fixture = TestBed.createComponent(TestComponent); - comp = fixture.componentInstance; debugElement = fixture.debugElement; profileService = fixture.debugElement.injector.get(ProfileService); @@ -52,8 +49,6 @@ describe('BuildPlanLinkDirective', () => { profileInfoSubject = new BehaviorSubject(profileInfo); getProfileInfoStub.returns(profileInfoSubject); - - correctBuildPlan = `https://some.url.com/plans/${comp.buildPlanId}/path/${comp.projectKey}`; }); }); diff --git a/src/test/javascript/spec/component/shared/delete-dialog-directive.spec.ts b/src/test/javascript/spec/directive/delete-dialog.directive.spec.ts similarity index 98% rename from src/test/javascript/spec/component/shared/delete-dialog-directive.spec.ts rename to src/test/javascript/spec/directive/delete-dialog.directive.spec.ts index 91e206f24ec9..04bb48c5e433 100644 --- a/src/test/javascript/spec/component/shared/delete-dialog-directive.spec.ts +++ b/src/test/javascript/spec/directive/delete-dialog.directive.spec.ts @@ -3,7 +3,7 @@ import { TranslateModule, TranslateService } from '@ngx-translate/core'; import { Component, DebugElement } from '@angular/core'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; -import { ArtemisTestModule } from '../../test.module'; +import { ArtemisTestModule } from '../test.module'; import { By } from '@angular/platform-browser'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { JhiAlertService, NgJhipsterModule } from 'ng-jhipster'; diff --git a/src/test/javascript/spec/helpers/mock-account.service.ts b/src/test/javascript/spec/helpers/mock-account.service.ts deleted file mode 100644 index af0bc5445670..000000000000 --- a/src/test/javascript/spec/helpers/mock-account.service.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { SpyObject } from './spyobject'; -import { AccountService } from 'app/core/auth/account.service'; -import Spy = jasmine.Spy; - -export class MockAccountService extends SpyObject { - getSpy: Spy; - saveSpy: Spy; - fakeResponse: any; - hasAnyAuthorityDirectSpy: Spy; - identitySpy: Spy; - isAtLeastInstructorInCourseSpy: Spy; - - constructor() { - super(AccountService); - - this.fakeResponse = null; - this.getSpy = this.spy('get').andReturn(this); - this.saveSpy = this.spy('save').andReturn(this); - this.hasAnyAuthorityDirectSpy = this.spy('hasAnyAuthorityDirect').andReturn(this); - this.identitySpy = this.spy('identity').andReturn(this); - this.isAtLeastInstructorInCourseSpy = this.spy('isAtLeastInstructorInCourse').andReturn(this); - } - - subscribe(callback: any) { - callback(this.fakeResponse); - } - - setResponse(json: any): void { - this.fakeResponse = json; - } -} diff --git a/src/test/javascript/spec/helpers/mock-websocket.service.ts b/src/test/javascript/spec/helpers/mock-websocket.service.ts deleted file mode 100644 index fbaeabd21b87..000000000000 --- a/src/test/javascript/spec/helpers/mock-websocket.service.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { SpyObject } from './spyobject'; -import { JhiWebsocketService } from '../../../../main/webapp/app/core/websocket/websocket.service'; - -export class MockTrackerService extends SpyObject { - constructor() { - super(JhiWebsocketService); - } - - connect() {} -} diff --git a/src/test/javascript/spec/helpers/mock-activated-route-query-param-map.ts b/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-query-param-map.ts similarity index 100% rename from src/test/javascript/spec/helpers/mock-activated-route-query-param-map.ts rename to src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-query-param-map.ts diff --git a/src/test/javascript/spec/helpers/mock-activated-route-snapshot.ts b/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-snapshot.ts similarity index 100% rename from src/test/javascript/spec/helpers/mock-activated-route-snapshot.ts rename to src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-snapshot.ts diff --git a/src/test/javascript/spec/mocks/mock-activated.route.ts b/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-with-subjects.ts similarity index 83% rename from src/test/javascript/spec/mocks/mock-activated.route.ts rename to src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-with-subjects.ts index 615041b93048..28ca21214cc9 100644 --- a/src/test/javascript/spec/mocks/mock-activated.route.ts +++ b/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route-with-subjects.ts @@ -1,7 +1,7 @@ import { Subject } from 'rxjs'; import { Params } from '@angular/router'; -export class MockActivatedRoute { +export class MockActivatedRouteWithSubjects { private subject = new Subject(); params = this.subject; diff --git a/src/test/javascript/spec/helpers/mock-route.service.ts b/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route.ts similarity index 59% rename from src/test/javascript/spec/helpers/mock-route.service.ts rename to src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route.ts index 031703f446e2..8bfc6aa3a7dc 100644 --- a/src/test/javascript/spec/helpers/mock-route.service.ts +++ b/src/test/javascript/spec/helpers/mocks/activated-route/mock-activated-route.ts @@ -1,7 +1,5 @@ -import { ActivatedRoute, Router } from '@angular/router'; -import { SpyObject } from './spyobject'; +import { ActivatedRoute } from '@angular/router'; import { of } from 'rxjs'; -import Spy = jasmine.Spy; export class MockActivatedRoute extends ActivatedRoute { constructor(parameters?: any) { @@ -18,12 +16,3 @@ export class MockActivatedRoute extends ActivatedRoute { }); } } - -export class MockRouter extends SpyObject { - navigateSpy: Spy; - - constructor() { - super(Router); - this.navigateSpy = this.spy('navigate'); - } -} diff --git a/src/test/javascript/spec/mocks/mock-has-any-authority.directive.ts b/src/test/javascript/spec/helpers/mocks/directive/mock-has-any-authority.directive.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-has-any-authority.directive.ts rename to src/test/javascript/spec/helpers/mocks/directive/mock-has-any-authority.directive.ts diff --git a/src/test/javascript/spec/mocks/mock-router.service.ts b/src/test/javascript/spec/helpers/mocks/mock-router.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-router.service.ts rename to src/test/javascript/spec/helpers/mocks/mock-router.ts diff --git a/src/test/javascript/spec/mocks/mock-account.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-account.service.ts similarity index 83% rename from src/test/javascript/spec/mocks/mock-account.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-account.service.ts index 3826256058ea..5138553a6ee4 100644 --- a/src/test/javascript/spec/mocks/mock-account.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-account.service.ts @@ -6,9 +6,9 @@ import { User } from 'app/core/user/user.model'; export class MockAccountService implements IAccountService { identity = () => Promise.resolve({ id: 99 } as User); hasAnyAuthority = (authorities: any[]) => Promise.resolve(true); - hasAnyAuthorityDirect = (authorities: any[]) => true; + hasAnyAuthorityDirect = (authorities: any[]) => authorities.length !== 0; getAuthenticationState = () => of({ id: 99 } as User); - isAtLeastInstructorInCourse = (course: Course) => true; + isAtLeastInstructorInCourse = (course: Course) => course.isAtLeastInstructor; authenticate = (identity: User | null) => {}; fetch = () => of({ body: { id: 99 } as User } as any); getImageUrl = () => 'blob'; diff --git a/src/test/javascript/spec/helpers/mock-active-modal.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-active-modal.service.ts similarity index 86% rename from src/test/javascript/spec/helpers/mock-active-modal.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-active-modal.service.ts index 8bf0cc966fa3..adcccbc9bc09 100644 --- a/src/test/javascript/spec/helpers/mock-active-modal.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-active-modal.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; import Spy = jasmine.Spy; diff --git a/src/test/javascript/spec/helpers/mock-alert.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-alert.service.ts similarity index 73% rename from src/test/javascript/spec/helpers/mock-alert.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-alert.service.ts index 1a220f9fcb7a..3d1b926c21bb 100644 --- a/src/test/javascript/spec/helpers/mock-alert.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-alert.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { JhiAlert, JhiAlertService } from 'ng-jhipster'; export class MockAlertService extends SpyObject { @@ -8,4 +8,6 @@ export class MockAlertService extends SpyObject { addAlert(alertOptions: JhiAlert) { return alertOptions; } + clear = () => {}; + error = () => {}; } diff --git a/src/test/javascript/spec/mocks/mock-auth-server-provider.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-auth-server-provider.service.ts similarity index 53% rename from src/test/javascript/spec/mocks/mock-auth-server-provider.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-auth-server-provider.service.ts index 287049f0974e..fa7a56dbf65f 100644 --- a/src/test/javascript/spec/mocks/mock-auth-server-provider.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-auth-server-provider.service.ts @@ -1,11 +1,12 @@ import { Credentials, IAuthServerProvider } from 'app/core/auth/auth-jwt.service'; +import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs'; export class MockAuthServerProviderService implements IAuthServerProvider { getToken = () => 'abc'; - login = (credentials: Credentials) => of('abc'); - loginWithToken = (jwt: string, rememberMe: string) => Promise.resolve('abc'); + login = (credentials: Credentials) => Observable.empty(); + loginWithToken = (jwt: string, rememberMe: boolean) => Promise.resolve('abc'); removeAuthTokenFromCaches = () => of(null); clearCaches = () => of(null); - storeAuthenticationToken = (jwt: string, rememberMe: string) => {}; + storeAuthenticationToken = (jwt: string, rememberMe: boolean) => {}; } diff --git a/src/test/javascript/spec/mocks/mock-cacheable-image.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-cacheable-image.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-cacheable-image.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-cacheable-image.service.ts diff --git a/src/test/javascript/spec/mocks/mock-code-editor-build-log.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-code-editor-build-log.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-code-editor-build-log.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-code-editor-build-log.service.ts diff --git a/src/test/javascript/spec/mocks/mock-code-editor-conflict-state.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-code-editor-conflict-state.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-code-editor-conflict-state.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-code-editor-conflict-state.service.ts diff --git a/src/test/javascript/spec/mocks/mock-code-editor-grid.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-code-editor-grid.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-code-editor-grid.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-code-editor-grid.service.ts diff --git a/src/test/javascript/spec/mocks/mock-code-editor-repository-file.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-code-editor-repository-file.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-code-editor-repository-file.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-code-editor-repository-file.service.ts diff --git a/src/test/javascript/spec/mocks/mock-code-editor-repository.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-code-editor-repository.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-code-editor-repository.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-code-editor-repository.service.ts diff --git a/src/test/javascript/spec/mocks/mock-code-editor-session.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-code-editor-session.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-code-editor-session.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-code-editor-session.service.ts diff --git a/src/test/javascript/spec/mocks/mock-complaint.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-complaint.service.ts similarity index 97% rename from src/test/javascript/spec/mocks/mock-complaint.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-complaint.service.ts index ba581ec11de1..36509821b859 100644 --- a/src/test/javascript/spec/mocks/mock-complaint.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-complaint.service.ts @@ -36,7 +36,7 @@ export class MockComplaintService implements IComplaintService { return of(); } findByResultId(resultId: number): Observable { - if (resultId == 111) { + if (resultId === 111) { return of(MockComplaintResponse2); } return of(MockComplaintResponse); diff --git a/src/test/javascript/spec/helpers/mocks/service/mock-cookie.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-cookie.service.ts new file mode 100644 index 000000000000..6873351c1493 --- /dev/null +++ b/src/test/javascript/spec/helpers/mocks/service/mock-cookie.service.ts @@ -0,0 +1,23 @@ +import { CookieService } from 'ngx-cookie-service'; + +export class MockCookieService extends CookieService { + get(key: string): string { + return ''; + } + + getAll(): any { + return {}; + } + + getObject(key: string): Object { + return {}; + } + + put(key: string, value: string, options?: any): void {} + + putObject(key: string, value: Object, options?: any): void {} + + remove(key: string, options?: any): void {} + + removeAll(options?: any): void {} +} diff --git a/src/test/javascript/spec/mocks/mock-course-exercise.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-course-exercise.service.ts similarity index 58% rename from src/test/javascript/spec/mocks/mock-course-exercise.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-course-exercise.service.ts index b0393d6d5c2f..e32de8dad885 100644 --- a/src/test/javascript/spec/mocks/mock-course-exercise.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-course-exercise.service.ts @@ -1,6 +1,9 @@ import { Observable } from 'rxjs'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; +import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; export class MockCourseExerciseService { startExercise = (courseId: number, exerciseId: number) => Observable.of({} as StudentParticipation); + + findAllProgrammingExercisesForCourse = (courseId: number) => Observable.of([{ id: 456 } as ProgrammingExercise]); } diff --git a/src/test/javascript/spec/helpers/mocks/service/mock-course-management.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-course-management.service.ts new file mode 100644 index 000000000000..522695469df6 --- /dev/null +++ b/src/test/javascript/spec/helpers/mocks/service/mock-course-management.service.ts @@ -0,0 +1,6 @@ +import { Observable } from 'rxjs'; +import { Course } from 'app/entities/course.model'; + +export class MockCourseManagementService { + find = (courseId: number) => Observable.of([{ id: 456 } as Course]); +} diff --git a/src/test/javascript/spec/mocks/mock-course.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-course.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-course.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-course.service.ts diff --git a/src/test/javascript/spec/helpers/mock-event-manager.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-event-manager.service.ts similarity index 85% rename from src/test/javascript/spec/helpers/mock-event-manager.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-event-manager.service.ts index a71b5d931421..7d9c1611c498 100644 --- a/src/test/javascript/spec/helpers/mock-event-manager.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-event-manager.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { JhiEventManager } from 'ng-jhipster'; import Spy = jasmine.Spy; diff --git a/src/test/javascript/spec/mocks/mock-exercise-hint.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-exercise-hint.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-exercise-hint.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-exercise-hint.service.ts diff --git a/src/test/javascript/spec/mocks/mock-exercise.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-exercise.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-exercise.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-exercise.service.ts diff --git a/src/test/javascript/spec/mocks/mock-feature-toggle-service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-feature-toggle.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-feature-toggle-service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-feature-toggle.service.ts diff --git a/src/test/javascript/spec/mocks/mock-file-upload-exercise.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-file-upload-exercise.service.ts similarity index 78% rename from src/test/javascript/spec/mocks/mock-file-upload-exercise.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-file-upload-exercise.service.ts index 40ef05044a55..adedf9bfa96e 100644 --- a/src/test/javascript/spec/mocks/mock-file-upload-exercise.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-file-upload-exercise.service.ts @@ -10,8 +10,8 @@ fileUploadExercise.filePattern = 'pdf,png'; fileUploadExercise.problemStatement = 'Example problem statement'; export class MockFileUploadExerciseService { - create = (fileUploadExercise: FileUploadExercise) => of(); - update = (fileUploadExercise: FileUploadExercise, exerciseId: number, req?: any) => of(); + create = (fileUploadExerciseParam: FileUploadExercise) => of(); + update = (fileUploadExerciseParam: FileUploadExercise, exerciseId: number, req?: any) => of(); find = (id: number) => of(new HttpResponse({ body: fileUploadExercise })); query = (req?: any) => of(); delete = (id: number) => of(); diff --git a/src/test/javascript/spec/mocks/mock-file-upload-submission.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-file-upload-submission.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-file-upload-submission.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-file-upload-submission.service.ts diff --git a/src/test/javascript/spec/mocks/mock-http.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-http.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-http.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-http.service.ts diff --git a/src/test/javascript/spec/mocks/mock-ide-build-and-test.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-ide-build-and-test.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-ide-build-and-test.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-ide-build-and-test.service.ts diff --git a/src/test/javascript/spec/helpers/mock-language.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-language.service.ts similarity index 79% rename from src/test/javascript/spec/helpers/mock-language.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-language.service.ts index 4bb69f6d765c..9cea996c7498 100644 --- a/src/test/javascript/spec/helpers/mock-language.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-language.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { JhiLanguageService } from 'ng-jhipster'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { of } from 'rxjs'; @@ -17,10 +17,13 @@ export class MockLanguageService extends SpyObject { init() {} + // eslint-disable-next-line @typescript-eslint/no-unused-vars changeLanguage(languageKey: string) {} + // eslint-disable-next-line @typescript-eslint/no-unused-vars setLocations(locations: string[]) {} + // eslint-disable-next-line @typescript-eslint/no-unused-vars addLocation(location: string) {} reload() {} diff --git a/src/test/javascript/spec/helpers/mock-login.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-login.service.ts similarity index 94% rename from src/test/javascript/spec/helpers/mock-login.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-login.service.ts index 93a8ca575f21..94f5706b636b 100644 --- a/src/test/javascript/spec/helpers/mock-login.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-login.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { LoginService } from 'app/core/login/login.service'; import Spy = jasmine.Spy; diff --git a/src/test/javascript/spec/mocks/mock-ngb-modal.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-ngb-modal.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-ngb-modal.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-ngb-modal.service.ts diff --git a/src/test/javascript/spec/mocks/mock-notification.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-notification.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-notification.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-notification.service.ts diff --git a/src/test/javascript/spec/mocks/mock-orion-connector.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-orion-connector.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-orion-connector.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-orion-connector.service.ts diff --git a/src/test/javascript/spec/mocks/mock-participation-websocket.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-participation-websocket.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-participation-websocket.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-participation-websocket.service.ts diff --git a/src/test/javascript/spec/mocks/mock-participation.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-participation.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-participation.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-participation.service.ts diff --git a/src/test/javascript/spec/helpers/mock-principal.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-principal.service.ts similarity index 90% rename from src/test/javascript/spec/helpers/mock-principal.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-principal.service.ts index cb1f175cd36d..e319bed856cb 100644 --- a/src/test/javascript/spec/helpers/mock-principal.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-principal.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { Principal } from 'app/core/auth/principal.service'; import Spy = jasmine.Spy; diff --git a/src/test/javascript/spec/mocks/mock-profile.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-profile.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-profile.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-profile.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-build-run.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-build-run.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-build-run.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-build-run.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-exercise-paging.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-paging.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-exercise-paging.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-paging.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-exercise-participation.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-participation.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-exercise-participation.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-participation.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-exercise-test-case.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-test-case.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-exercise-test-case.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-test-case.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-exercise-websocket.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-websocket.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-exercise-websocket.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise-websocket.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-exercise.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-exercise.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-exercise.service.ts diff --git a/src/test/javascript/spec/mocks/mock-programming-submission.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-programming-submission.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-programming-submission.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-programming-submission.service.ts diff --git a/src/test/javascript/spec/mocks/mock-repository-file.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-repository-file.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-repository-file.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-repository-file.service.ts diff --git a/src/test/javascript/spec/mocks/mock-result.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-result.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-result.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-result.service.ts diff --git a/src/test/javascript/spec/helpers/mock-state-storage.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-state-storage.service.ts similarity index 92% rename from src/test/javascript/spec/helpers/mock-state-storage.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-state-storage.service.ts index 19106b869ddc..eaf076ae773b 100644 --- a/src/test/javascript/spec/helpers/mock-state-storage.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-state-storage.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { StateStorageService } from 'app/core/auth/state-storage.service'; import Spy = jasmine.Spy; diff --git a/src/test/javascript/spec/mocks/mock-sync.storage.ts b/src/test/javascript/spec/helpers/mocks/service/mock-sync-storage.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-sync.storage.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-sync-storage.service.ts diff --git a/src/test/javascript/spec/mocks/mock-team.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-team.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-team.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-team.service.ts diff --git a/src/test/javascript/spec/mocks/mock-text-editor.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-text-editor.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-text-editor.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-text-editor.service.ts diff --git a/src/test/javascript/spec/helpers/mock-tracker.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-tracker.service.ts similarity index 81% rename from src/test/javascript/spec/helpers/mock-tracker.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-tracker.service.ts index 1b994f7b3d66..04b89d853e35 100644 --- a/src/test/javascript/spec/helpers/mock-tracker.service.ts +++ b/src/test/javascript/spec/helpers/mocks/service/mock-tracker.service.ts @@ -1,4 +1,4 @@ -import { SpyObject } from './spyobject'; +import { SpyObject } from '../../spyobject'; import { JhiTrackerService } from 'app/core/tracker/tracker.service'; export class MockTrackerService extends SpyObject { diff --git a/src/test/javascript/spec/mocks/mock-translate.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-translate.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-translate.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-translate.service.ts diff --git a/src/test/javascript/spec/mocks/mock-user.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-user.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-user.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-user.service.ts diff --git a/src/test/javascript/spec/mocks/mock-websocket.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-websocket.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-websocket.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-websocket.service.ts diff --git a/src/test/javascript/spec/mocks/mock-window.service.ts b/src/test/javascript/spec/helpers/mocks/service/mock-window.service.ts similarity index 100% rename from src/test/javascript/spec/mocks/mock-window.service.ts rename to src/test/javascript/spec/helpers/mocks/service/mock-window.service.ts diff --git a/src/test/javascript/spec/sample/build-logs.ts b/src/test/javascript/spec/helpers/sample/build-logs.ts similarity index 100% rename from src/test/javascript/spec/sample/build-logs.ts rename to src/test/javascript/spec/helpers/sample/build-logs.ts diff --git a/src/test/javascript/spec/sample/problemStatement.json b/src/test/javascript/spec/helpers/sample/problemStatement.json similarity index 100% rename from src/test/javascript/spec/sample/problemStatement.json rename to src/test/javascript/spec/helpers/sample/problemStatement.json diff --git a/src/test/javascript/spec/utils/general.utils.ts b/src/test/javascript/spec/helpers/utils/general.utils.ts similarity index 100% rename from src/test/javascript/spec/utils/general.utils.ts rename to src/test/javascript/spec/helpers/utils/general.utils.ts diff --git a/src/test/javascript/spec/integration/code-editor/code-editor-instructor.spec.ts b/src/test/javascript/spec/integration/code-editor/code-editor-instructor.integration.spec.ts similarity index 92% rename from src/test/javascript/spec/integration/code-editor/code-editor-instructor.spec.ts rename to src/test/javascript/spec/integration/code-editor/code-editor-instructor.integration.spec.ts index 330d92cd120b..ad421e18064a 100644 --- a/src/test/javascript/spec/integration/code-editor/code-editor-instructor.spec.ts +++ b/src/test/javascript/spec/integration/code-editor/code-editor-instructor.integration.spec.ts @@ -16,15 +16,15 @@ import { ArtemisTestModule } from '../../test.module'; import { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service'; import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; import { DomainType, FileType } from 'app/exercises/programming/shared/code-editor/model/code-editor.model'; -import { MockAccountService } from '../../mocks/mock-account.service'; -import { MockRouter } from '../../mocks/mock-router.service'; -import { problemStatement } from '../../sample/problemStatement.json'; -import { MockProgrammingExerciseParticipationService } from '../../mocks/mock-programming-exercise-participation.service'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; +import { MockRouter } from '../../helpers/mocks/mock-router'; +import { problemStatement } from '../../helpers/sample/problemStatement.json'; +import { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service'; import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { DeviceDetectorService } from 'ngx-device-detector'; import { CodeEditorInstructorContainerComponent } from 'app/exercises/programming/manage/code-editor/code-editor-instructor-container.component'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockCourseExerciseService } from '../../mocks/mock-course-exercise.service'; +import { MockCourseExerciseService } from '../../helpers/mocks/service/mock-course-exercise.service'; import { ExerciseHintService, IExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; import { CodeEditorBuildLogService, @@ -40,19 +40,19 @@ import { ParticipationService } from 'app/exercises/shared/participation/partici import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { ProgrammingExerciseStudentParticipation } from 'app/entities/participation/programming-exercise-student-participation.model'; import { SolutionProgrammingExerciseParticipation } from 'app/entities/participation/solution-programming-exercise-participation.model'; -import { MockActivatedRoute } from '../../mocks/mock-activated.route'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockResultService } from '../../mocks/mock-result.service'; -import { MockCodeEditorRepositoryService } from '../../mocks/mock-code-editor-repository.service'; -import { MockCodeEditorBuildLogService } from '../../mocks/mock-code-editor-build-log.service'; -import { MockCodeEditorRepositoryFileService } from '../../mocks/mock-code-editor-repository-file.service'; -import { MockCodeEditorSessionService } from '../../mocks/mock-code-editor-session.service'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockParticipationService } from '../../mocks/mock-participation.service'; -import { MockProgrammingExerciseService } from '../../mocks/mock-programming-exercise.service'; -import { MockExerciseHintService } from '../../mocks/mock-exercise-hint.service'; +import { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockResultService } from '../../helpers/mocks/service/mock-result.service'; +import { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service'; +import { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service'; +import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service'; +import { MockCodeEditorSessionService } from '../../helpers/mocks/service/mock-code-editor-session.service'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockParticipationService } from '../../helpers/mocks/service/mock-participation.service'; +import { MockProgrammingExerciseService } from '../../helpers/mocks/service/mock-programming-exercise.service'; +import { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service'; import { JhiWebsocketService } from 'app/core/websocket/websocket.service'; -import { MockWebsocketService } from '../../mocks/mock-websocket.service'; +import { MockWebsocketService } from '../../helpers/mocks/service/mock-websocket.service'; import { ArtemisCodeEditorManagementModule } from 'app/exercises/programming/manage/code-editor/code-editor-management.module'; import { CourseExerciseService } from 'app/course/manage/course-management.service'; @@ -76,7 +76,6 @@ describe('CodeEditorInstructorIntegration', () => { let domainService: DomainService; let exerciseHintService: IExerciseHintService; let route: ActivatedRoute; - let router: Router; let checkIfRepositoryIsCleanStub: SinonStub; let getRepositoryContentStub: SinonStub; @@ -110,7 +109,7 @@ describe('CodeEditorInstructorIntegration', () => { DeviceDetectorService, { provide: Router, useClass: MockRouter }, { provide: AccountService, useClass: MockAccountService }, - { provide: ActivatedRoute, useClass: MockActivatedRoute }, + { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects }, { provide: SessionStorageService, useClass: MockSyncStorage }, { provide: ResultService, useClass: MockResultService }, { provide: LocalStorageService, useClass: MockSyncStorage }, @@ -145,7 +144,7 @@ describe('CodeEditorInstructorIntegration', () => { domainService = containerDebugElement.injector.get(DomainService); exerciseHintService = containerDebugElement.injector.get(ExerciseHintService); route = containerDebugElement.injector.get(ActivatedRoute); - router = containerDebugElement.injector.get(Router); + containerDebugElement.injector.get(Router); checkIfRepositoryIsCleanSubject = new Subject<{ isClean: boolean }>(); getRepositoryContentSubject = new Subject<{ [fileName: string]: FileType }>(); @@ -154,7 +153,7 @@ describe('CodeEditorInstructorIntegration', () => { routeSubject = new Subject(); // @ts-ignore - (route as MockActivatedRoute).setSubject(routeSubject); + (route as MockActivatedRouteWithSubjects).setSubject(routeSubject); checkIfRepositoryIsCleanStub = stub(codeEditorRepositoryService, 'getStatus'); getRepositoryContentStub = stub(codeEditorRepositoryFileService, 'getRepositoryContent'); @@ -195,7 +194,7 @@ describe('CodeEditorInstructorIntegration', () => { routeSubject = new Subject(); // @ts-ignore - (route as MockActivatedRoute).setSubject(routeSubject); + (route as MockActivatedRouteWithSubjects).setSubject(routeSubject); findWithParticipationsSubject = new Subject<{ body: ProgrammingExercise }>(); findWithParticipationsStub.returns(findWithParticipationsSubject); diff --git a/src/test/javascript/spec/integration/code-editor/code-editor-student.spec.ts b/src/test/javascript/spec/integration/code-editor/code-editor-student.integration.spec.ts similarity index 93% rename from src/test/javascript/spec/integration/code-editor/code-editor-student.spec.ts rename to src/test/javascript/spec/integration/code-editor/code-editor-student.integration.spec.ts index 24df29602a7c..d1f7235397bd 100644 --- a/src/test/javascript/spec/integration/code-editor/code-editor-student.spec.ts +++ b/src/test/javascript/spec/integration/code-editor/code-editor-student.integration.spec.ts @@ -17,19 +17,19 @@ import { ArtemisTestModule } from '../../test.module'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; import { ProgrammingExerciseParticipationService } from 'app/exercises/programming/manage/services/programming-exercise-participation.service'; import { CommitState, DeleteFileChange, DomainType, EditorState, FileType, GitConflictState } from 'app/exercises/programming/shared/code-editor/model/code-editor.model'; -import { buildLogs, extractedBuildLogErrors } from '../../sample/build-logs'; -import { problemStatement } from '../../sample/problemStatement.json'; -import { MockAccountService } from '../../mocks/mock-account.service'; -import { MockProgrammingExerciseParticipationService } from '../../mocks/mock-programming-exercise-participation.service'; +import { buildLogs, extractedBuildLogErrors } from '../../helpers/sample/build-logs'; +import { problemStatement } from '../../helpers/sample/problemStatement.json'; +import { MockAccountService } from '../../helpers/mocks/service/mock-account.service'; +import { MockProgrammingExerciseParticipationService } from '../../helpers/mocks/service/mock-programming-exercise-participation.service'; import { ProgrammingSubmissionService, ProgrammingSubmissionState, ProgrammingSubmissionStateObj } from 'app/exercises/programming/participate/programming-submission.service'; -import { MockProgrammingSubmissionService } from '../../mocks/mock-programming-submission.service'; +import { MockProgrammingSubmissionService } from '../../helpers/mocks/service/mock-programming-submission.service'; import { ExerciseHint } from 'app/entities/exercise-hint.model'; import { DeviceDetectorService } from 'ngx-device-detector'; import { GuidedTourService } from 'app/guided-tour/guided-tour.service'; -import { getElement } from '../../utils/general.utils'; +import { getElement } from '../../helpers/utils/general.utils'; import { GuidedTourMapping } from 'app/guided-tour/guided-tour-setting.model'; import { JhiWebsocketService } from 'app/core/websocket/websocket.service'; -import { MockWebsocketService } from '../../mocks/mock-websocket.service'; +import { MockWebsocketService } from '../../helpers/mocks/service/mock-websocket.service'; import { Participation } from 'app/entities/participation/participation.model'; import { BuildLogEntryArray } from 'app/entities/build-log.model'; import { CodeEditorConflictStateService } from 'app/exercises/programming/shared/code-editor/service/code-editor-conflict-state.service'; @@ -48,15 +48,15 @@ import { CodeEditorSessionService } from 'app/exercises/programming/shared/code- import { DomainService } from 'app/exercises/programming/shared/code-editor/service/code-editor-domain.service'; import { ProgrammingSubmission } from 'app/entities/programming-submission.model'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; -import { MockActivatedRoute } from '../../mocks/mock-activated.route'; -import { MockParticipationWebsocketService } from '../../mocks/mock-participation-websocket.service'; -import { MockSyncStorage } from '../../mocks/mock-sync.storage'; -import { MockResultService } from '../../mocks/mock-result.service'; -import { MockCodeEditorRepositoryService } from '../../mocks/mock-code-editor-repository.service'; -import { MockExerciseHintService } from '../../mocks/mock-exercise-hint.service'; -import { MockCodeEditorRepositoryFileService } from '../../mocks/mock-code-editor-repository-file.service'; -import { MockCodeEditorSessionService } from '../../mocks/mock-code-editor-session.service'; -import { MockCodeEditorBuildLogService } from '../../mocks/mock-code-editor-build-log.service'; +import { MockActivatedRouteWithSubjects } from '../../helpers/mocks/activated-route/mock-activated-route-with-subjects'; +import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; +import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; +import { MockResultService } from '../../helpers/mocks/service/mock-result.service'; +import { MockCodeEditorRepositoryService } from '../../helpers/mocks/service/mock-code-editor-repository.service'; +import { MockExerciseHintService } from '../../helpers/mocks/service/mock-exercise-hint.service'; +import { MockCodeEditorRepositoryFileService } from '../../helpers/mocks/service/mock-code-editor-repository-file.service'; +import { MockCodeEditorSessionService } from '../../helpers/mocks/service/mock-code-editor-session.service'; +import { MockCodeEditorBuildLogService } from '../../helpers/mocks/service/mock-code-editor-build-log.service'; import { ArtemisProgrammingParticipationModule } from 'app/exercises/programming/participate/programming-participation.module'; chai.use(sinonChai); @@ -111,7 +111,7 @@ describe('CodeEditorStudentIntegration', () => { DeviceDetectorService, CodeEditorConflictStateService, { provide: AccountService, useClass: MockAccountService }, - { provide: ActivatedRoute, useClass: MockActivatedRoute }, + { provide: ActivatedRoute, useClass: MockActivatedRouteWithSubjects }, { provide: JhiWebsocketService, useClass: MockWebsocketService }, { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService }, { provide: ProgrammingExerciseParticipationService, useClass: MockProgrammingExerciseParticipationService }, @@ -150,7 +150,7 @@ describe('CodeEditorStudentIntegration', () => { routeSubject = new Subject(); // @ts-ignore - (route as MockActivatedRoute).setSubject(routeSubject); + (route as MockActivatedRouteWithSubjects).setSubject(routeSubject); getLatestPendingSubmissionSubject = new Subject(); @@ -186,7 +186,7 @@ describe('CodeEditorStudentIntegration', () => { routeSubject = new Subject(); // @ts-ignore - (route as MockActivatedRoute).setSubject(routeSubject); + (route as MockActivatedRouteWithSubjects).setSubject(routeSubject); getLatestPendingSubmissionSubject = new Subject(); getLatestPendingSubmissionStub.returns(getLatestPendingSubmissionSubject); @@ -440,7 +440,7 @@ describe('CodeEditorStudentIntegration', () => { it('should wait for build result after submission if no unsaved changes exist', () => { cleanInitialize(); - const result = { id: 4, successful: true, feedbacks: [] as Feedback[], participation: { id: 3 } } as Result; + const successfulResult = { id: 4, successful: true, feedbacks: [] as Feedback[], participation: { id: 3 } } as Result; const expectedBuildLog = new BuildLogEntryArray(); expect(container.unsavedFiles).to.be.empty; container.commitState = CommitState.UNCOMMITTED_CHANGES; @@ -452,21 +452,21 @@ describe('CodeEditorStudentIntegration', () => { getLatestPendingSubmissionSubject.next({ submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: {} as ProgrammingSubmission, - participationId: result!.participation!.id, + participationId: successfulResult!.participation!.id, }); container.actions.commit(); containerFixture.detectChanges(); - // waiting for build result + // waiting for build successfulResult expect(container.commitState).to.equal(CommitState.CLEAN); expect(container.buildOutput.isBuilding).to.be.true; getLatestPendingSubmissionSubject.next({ submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: null, - participationId: result!.participation!.id, + participationId: successfulResult!.participation!.id, }); - subscribeForLatestResultOfParticipationSubject.next(result); + subscribeForLatestResultOfParticipationSubject.next(successfulResult); containerFixture.detectChanges(); expect(container.buildOutput.isBuilding).to.be.false; @@ -603,9 +603,8 @@ describe('CodeEditorStudentIntegration', () => { spyOn(guidedTourService, 'checkTourState').and.returnValue(true); guidedTourService.guidedTourMapping = guidedTourMapping; container.ngOnInit(); - const exercise = { id: 1, problemStatement }; - const result = { id: 3, successful: false }; - const participation = { id: 1, results: [result], exercise: { id: 99 } } as Participation; + const successfulResult = { id: 3, successful: false }; + const participation = { id: 1, results: [successfulResult], exercise: { id: 99 } } as Participation; const feedbacks = [{ id: 2 }] as Feedback[]; const findWithLatestResultSubject = new Subject(); const getFeedbackDetailsForResultSubject = new Subject<{ body: Feedback[] }>(); diff --git a/src/test/javascript/spec/mocks/mock-activated-route.ts b/src/test/javascript/spec/mocks/mock-activated-route.ts deleted file mode 100644 index 8a34fda18f9f..000000000000 --- a/src/test/javascript/spec/mocks/mock-activated-route.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Params } from '@angular/router'; -import { BehaviorSubject } from 'rxjs'; - -export class MockActivatedRoute { - private innerTestParams?: any; - private subject: BehaviorSubject = new BehaviorSubject(this.testParams); - - params = this.subject.asObservable(); - - constructor(params?: Params) { - if (params) { - this.testParams = params; - } else { - this.testParams = {}; - } - } - - get testParams() { - return this.innerTestParams; - } - - set testParams(params: {}) { - this.innerTestParams = params; - this.subject.next(params); - } -} diff --git a/src/test/javascript/spec/mocks/mock-alert.service.ts b/src/test/javascript/spec/mocks/mock-alert.service.ts deleted file mode 100644 index 6cb9b85a47ed..000000000000 --- a/src/test/javascript/spec/mocks/mock-alert.service.ts +++ /dev/null @@ -1,4 +0,0 @@ -export class MockAlertService { - clear = () => {}; - error = () => {}; -} diff --git a/src/test/javascript/spec/mocks/mock-cookie.service.ts b/src/test/javascript/spec/mocks/mock-cookie.service.ts deleted file mode 100644 index 2736019064bf..000000000000 --- a/src/test/javascript/spec/mocks/mock-cookie.service.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { CookieOptions, ICookieService } from 'ngx-cookie-service'; - -export class MockCookieService implements ICookieService { - get(key: string): string { - return ''; - } - - getAll(): Object { - return {}; - } - - getObject(key: string): Object { - return {}; - } - - put(key: string, value: string, options?: CookieOptions): void {} - - putObject(key: string, value: Object, options?: CookieOptions): void {} - - remove(key: string, options?: CookieOptions): void {} - - removeAll(options?: CookieOptions): void {} -} diff --git a/src/test/javascript/spec/service/account-service.spec.ts b/src/test/javascript/spec/service/account.service.spec.ts similarity index 85% rename from src/test/javascript/spec/service/account-service.spec.ts rename to src/test/javascript/spec/service/account.service.spec.ts index ca5915ded337..beb66117c2ad 100644 --- a/src/test/javascript/spec/service/account-service.spec.ts +++ b/src/test/javascript/spec/service/account.service.spec.ts @@ -1,15 +1,15 @@ import { async } from '@angular/core/testing'; import * as chai from 'chai'; import { SinonStub, stub } from 'sinon'; -import { Observable, of } from 'rxjs'; +import { of } from 'rxjs'; import * as sinonChai from 'sinon-chai'; -import { MockWebsocketService } from '../mocks/mock-websocket.service'; -import { MockLanguageService } from '../helpers/mock-language.service'; -import { MockHttpService } from '../mocks/mock-http.service'; -import { MockFeatureToggleService } from '../mocks/mock-feature-toggle-service'; +import { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service'; +import { MockLanguageService } from '../helpers/mocks/service/mock-language.service'; +import { MockHttpService } from '../helpers/mocks/service/mock-http.service'; +import { MockFeatureToggleService } from '../helpers/mocks/service/mock-feature-toggle.service'; import { User } from 'app/core/user/user.model'; import { AccountService } from 'app/core/auth/account.service'; -import { MockSyncStorage } from '../mocks/mock-sync.storage'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; chai.use(sinonChai); const expect = chai.expect; @@ -18,7 +18,6 @@ describe('AccountService', () => { let accountService: AccountService; let httpService: MockHttpService; let getStub: SinonStub; - let getAuthenticated: Observable; const getUserUrl = 'undefinedapi/account'; const user = { id: 1, groups: ['USER'] } as User; @@ -29,7 +28,6 @@ describe('AccountService', () => { // @ts-ignore accountService = new AccountService(new MockLanguageService(), new MockSyncStorage(), httpService, new MockWebsocketService(), new MockFeatureToggleService()); getStub = stub(httpService, 'get'); - getAuthenticated = accountService.getAuthenticationState(); expect(accountService.userIdentity).to.deep.equal(null); expect(accountService.isAuthenticated()).to.be.false; diff --git a/src/test/javascript/spec/service/audits.service.spec.ts b/src/test/javascript/spec/service/audits.service.spec.ts new file mode 100644 index 000000000000..21806d4c672e --- /dev/null +++ b/src/test/javascript/spec/service/audits.service.spec.ts @@ -0,0 +1,57 @@ +import { TestBed } from '@angular/core/testing'; + +import { AuditsService } from 'app/admin/audits/audits.service'; +import { Audit } from 'app/admin/audits/audit.model'; +import { SERVER_API_URL } from 'app/app.constants'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +describe('Audits Service', () => { + let service: AuditsService; + let httpMock; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + + service = TestBed.inject(AuditsService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + describe('Service methods', () => { + it('should call correct URL', () => { + service.query({}).subscribe(() => {}); + + const req = httpMock.expectOne({ method: 'GET' }); + const resourceUrl = SERVER_API_URL + 'management/audits'; + expect(req.request.url).toEqual(resourceUrl); + }); + + it('should return Audits', () => { + const audit = new Audit({ remoteAddress: '127.0.0.1', sessionId: '123' }, 'user', '20140101', 'AUTHENTICATION_SUCCESS'); + + service.query({}).subscribe((received) => { + expect(received.body[0]).toEqual(audit); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([audit]); + }); + + it('should propagate not found response', () => { + service.query({}).subscribe(null, (_error: any) => { + expect(_error.status).toEqual(404); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush('Invalid request parameters', { + status: 404, + statusText: 'Bad Request', + }); + }); + }); +}); diff --git a/src/test/javascript/spec/service/configuration.service.spec.ts b/src/test/javascript/spec/service/configuration.service.spec.ts new file mode 100644 index 000000000000..668b94240587 --- /dev/null +++ b/src/test/javascript/spec/service/configuration.service.spec.ts @@ -0,0 +1,65 @@ +import { TestBed } from '@angular/core/testing'; + +import { JhiConfigurationService } from 'app/admin/configuration/configuration.service'; +import { SERVER_API_URL } from 'app/app.constants'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpResponse } from '@angular/common/http'; + +describe('Logs Service', () => { + let service: JhiConfigurationService; + let httpMock; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + + service = TestBed.inject(JhiConfigurationService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + describe('Service methods', () => { + it('should call correct URL', () => { + service.get().subscribe(() => {}); + + const req = httpMock.expectOne({ method: 'GET' }); + const resourceUrl = SERVER_API_URL + 'management/configprops'; + expect(req.request.url).toEqual(resourceUrl); + }); + + it('should get the config', () => { + const angularConfig = { + contexts: { + angular: { + beans: ['test2'], + }, + }, + }; + service.get().subscribe((received) => { + expect(received.body[0]).toEqual(angularConfig); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(angularConfig); + }); + + it('should get the env', () => { + const propertySources = new HttpResponse({ + body: [ + { name: 'test1', properties: 'test1' }, + { name: 'test2', properties: 'test2' }, + ], + }); + service.get().subscribe((received) => { + expect(received.body[0]).toEqual(propertySources); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(propertySources); + }); + }); +}); diff --git a/src/test/javascript/spec/service/course.service.spec.ts b/src/test/javascript/spec/service/course.service.spec.ts new file mode 100644 index 000000000000..69298814d08d --- /dev/null +++ b/src/test/javascript/spec/service/course.service.spec.ts @@ -0,0 +1,162 @@ +import { TranslateService } from '@ngx-translate/core'; +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { Router } from '@angular/router'; +import { map, take } from 'rxjs/operators'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import * as moment from 'moment'; +import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; +import { CourseManagementService } from 'app/course/manage/course-management.service'; +import { Course } from 'app/entities/course.model'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { MockRouter } from '../helpers/mocks/mock-router'; + +describe('Course Service', () => { + let injector: TestBed; + let service: CourseManagementService; + let httpMock: HttpTestingController; + let elemDefault: Course; + let currentDate: moment.Moment; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [ + { provide: Router, useClass: MockRouter }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }); + injector = getTestBed(); + service = injector.get(CourseManagementService); + httpMock = injector.get(HttpTestingController); + currentDate = moment(); + + elemDefault = new Course(); + elemDefault.id = 0; + elemDefault.title = 'AAAAAAA'; + elemDefault.description = 'AAAAAAA'; + elemDefault.shortName = 'AAAAAAA'; + elemDefault.title = 'AAAAAAA'; + elemDefault.startDate = currentDate; + elemDefault.endDate = currentDate; + elemDefault.complaintsEnabled = false; + elemDefault.studentQuestionsEnabled = false; + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign( + { + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT), + }, + elemDefault, + ); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a Course', async () => { + const returnedFromService = Object.assign( + { + id: 0, + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT), + }, + elemDefault, + ); + const expected = Object.assign( + { + startDate: currentDate, + endDate: currentDate, + }, + returnedFromService, + ); + service + .create(new Course()) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a Course', async () => { + const returnedFromService = Object.assign( + { + title: 'BBBBBB', + studentGroupName: 'BBBBBB', + teachingAssistantGroupName: 'BBBBBB', + instructorGroupName: 'BBBBBB', + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT), + onlineCourse: true, + }, + elemDefault, + ); + + const expected = Object.assign( + { + startDate: currentDate, + endDate: currentDate, + }, + returnedFromService, + ); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of Course', async () => { + const returnedFromService = Object.assign( + { + title: 'BBBBBB', + studentGroupName: 'BBBBBB', + teachingAssistantGroupName: 'BBBBBB', + instructorGroupName: 'BBBBBB', + startDate: currentDate.format(DATE_TIME_FORMAT), + endDate: currentDate.format(DATE_TIME_FORMAT), + onlineCourse: true, + }, + elemDefault, + ); + const expected = Object.assign( + { + startDate: currentDate, + endDate: currentDate, + }, + returnedFromService, + ); + service + .findAll(expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a Course', async () => { + service.delete(123).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/delete-dialog-service.spec.ts b/src/test/javascript/spec/service/delete-dialog.service.spec.ts similarity index 92% rename from src/test/javascript/spec/service/delete-dialog-service.spec.ts rename to src/test/javascript/spec/service/delete-dialog.service.spec.ts index e5790118991b..788d6f011426 100644 --- a/src/test/javascript/spec/service/delete-dialog-service.spec.ts +++ b/src/test/javascript/spec/service/delete-dialog.service.spec.ts @@ -7,11 +7,11 @@ import { ArtemisTestModule } from '../test.module'; import { DeleteDialogService } from 'app/shared/delete-dialog/delete-dialog.service'; import { NgbModal } from '@ng-bootstrap/ng-bootstrap'; import * as sinon from 'sinon'; -import { DeleteDialogComponent } from 'app/shared/delete-dialog/delete-dialog.component'; import { TranslateModule } from '@ngx-translate/core'; import { AlertService } from 'app/core/alert/alert.service'; import { ActionType, DeleteDialogData } from 'app/shared/delete-dialog/delete-dialog.model'; import { EventEmitter } from '@angular/core'; +import { Observable } from 'rxjs'; chai.use(sinonChai); const expect = chai.expect; @@ -33,6 +33,7 @@ describe('Delete Dialog Service', () => { it('should open delete dialog', () => { expect(service.modalRef).to.be.undefined; const data: DeleteDialogData = { + dialogError: new Observable(), entityTitle: 'title', deleteQuestion: 'artemisApp.exercise.delete.question', deleteConfirmationText: 'artemisApp.exercise.delete.typeNameToConfirm', @@ -42,8 +43,7 @@ describe('Delete Dialog Service', () => { const modalSpy = sinon.spy(modalService, 'open'); service.openDeleteDialog(data); expect(modalSpy.callCount).to.be.equal(1); - let call = modalSpy.getCall(0); - let args = call.args; + const args = modalSpy.getCall(0).args; expect(args[0].name).to.be.equal('DeleteDialogComponent'); expect(args[1]).to.be.not.null; }); diff --git a/src/test/javascript/spec/service/exercise-hint.service.spec.ts b/src/test/javascript/spec/service/exercise-hint.service.spec.ts new file mode 100644 index 000000000000..0191614e3469 --- /dev/null +++ b/src/test/javascript/spec/service/exercise-hint.service.spec.ts @@ -0,0 +1,94 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpResponse } from '@angular/common/http'; +import * as chai from 'chai'; +import { take } from 'rxjs/operators'; +import { ExerciseHintService } from 'app/exercises/shared/exercise-hint/manage/exercise-hint.service'; +import { ExerciseHint } from 'app/entities/exercise-hint.model'; + +const expect = chai.expect; + +describe('ExerciseHint Service', () => { + let injector: TestBed; + let service: ExerciseHintService; + let httpMock: HttpTestingController; + let elemDefault: ExerciseHint; + let expectedResult: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + expectedResult = {} as HttpResponse; + injector = getTestBed(); + service = injector.get(ExerciseHintService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new ExerciseHint(); + elemDefault.id = 0; + elemDefault.title = 'AAAAAAA'; + elemDefault.content = 'AAAAAAA'; + }); + + describe('Service methods', () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(elemDefault); + }); + + it('should create a ExerciseHint', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new ExerciseHint()) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should update a ExerciseHint', async () => { + const returnedFromService = Object.assign( + { + title: 'BBBBBB', + content: 'BBBBBB', + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should delete a ExerciseHint', async () => { + service.delete(123).subscribe((resp) => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult).to.be.true; + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/file-upload-exercise.service.spec.ts b/src/test/javascript/spec/service/file-upload-exercise.service.spec.ts new file mode 100644 index 000000000000..cc47c02ca93e --- /dev/null +++ b/src/test/javascript/spec/service/file-upload-exercise.service.spec.ts @@ -0,0 +1,117 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { map, take } from 'rxjs/operators'; + +import { FileUploadExerciseService } from 'app/exercises/file-upload/manage/file-upload-exercise.service'; +import { FileUploadExercise } from 'app/entities/file-upload-exercise.model'; +import { ArtemisTestModule } from '../test.module'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { TranslateService } from '@ngx-translate/core'; +import { Course } from 'app/entities/course.model'; + +describe('FileUploadExercise Service', () => { + let injector: TestBed; + let service: FileUploadExerciseService; + let httpMock: HttpTestingController; + let elemDefault: FileUploadExercise; + + const course: Course = { id: 123 } as Course; + const fileUploadExercise = new FileUploadExercise(course); + fileUploadExercise.id = 456; + fileUploadExercise.filePattern = 'pdf'; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule, HttpClientTestingModule], + providers: [ + { provide: LocalStorageService, useClass: MockSyncStorage }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }); + injector = getTestBed(); + service = injector.get(FileUploadExerciseService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new FileUploadExercise(0); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a FileUploadExercise', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(fileUploadExercise) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a FileUploadExercise', async () => { + const returnedFromService = Object.assign( + { + filePattern: 'BBBBBB', + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of FileUploadExercise', async () => { + const returnedFromService = Object.assign( + { + filePattern: 'BBBBBB', + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a FileUploadExercise', async () => { + service.delete(123).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/file-upload-submission.service.spec.ts b/src/test/javascript/spec/service/file-upload-submission.service.spec.ts new file mode 100644 index 000000000000..6acd5b141ecc --- /dev/null +++ b/src/test/javascript/spec/service/file-upload-submission.service.spec.ts @@ -0,0 +1,76 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { map, take } from 'rxjs/operators'; +import { FileUploadSubmissionService } from 'app/exercises/file-upload/participate/file-upload-submission.service'; +import { FileUploadSubmission } from 'app/entities/file-upload-submission.model'; + +describe('FileUploadSubmission Service', () => { + let injector: TestBed; + let service: FileUploadSubmissionService; + let httpMock: HttpTestingController; + let elemDefault: FileUploadSubmission; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + injector = getTestBed(); + service = injector.get(FileUploadSubmissionService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new FileUploadSubmission(); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .get(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create/update a FileUploadSubmission', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .update(new FileUploadSubmission(), 1, null) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of FileUploadSubmission for an exercise', async () => { + const returnedFromService = Object.assign( + { + filePath: 'BBBBBB', + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .getFileUploadSubmissionsForExercise(1, expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/guided-tour.service.spec.ts b/src/test/javascript/spec/service/guided-tour.service.spec.ts index 46a0977d13ce..791ad7e1f6cb 100644 --- a/src/test/javascript/spec/service/guided-tour.service.spec.ts +++ b/src/test/javascript/spec/service/guided-tour.service.spec.ts @@ -18,11 +18,11 @@ import { GuidedTourState, Orientation, ResetParticipation, UserInteractionEvent import { GuidedTourComponent } from 'app/guided-tour/guided-tour.component'; import { GuidedTourMapping, GuidedTourSetting } from 'app/guided-tour/guided-tour-setting.model'; import { ModelingTaskTourStep, TextTourStep, UserInterActionTourStep } from 'app/guided-tour/guided-tour-step.model'; -import { MockAccountService } from '../mocks/mock-account.service'; +import { MockAccountService } from '../helpers/mocks/service/mock-account.service'; import { AccountService } from 'app/core/auth/account.service'; import { DeviceDetectorService } from 'ngx-device-detector'; import { Course } from 'app/entities/course.model'; -import { MockTranslateService } from '../mocks/mock-translate.service'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; import { GuidedTourModelingTask, personUML } from 'app/guided-tour/guided-tour-task.model'; import { completedTour } from 'app/guided-tour/tours/general-tour'; import { SinonStub, stub } from 'sinon'; @@ -32,8 +32,8 @@ import { Exercise, ExerciseType } from 'app/entities/exercise.model'; import { InitializationState } from 'app/entities/participation/participation.model'; import { NavbarComponent } from 'app/shared/layouts/navbar/navbar.component'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; -import { MockSyncStorage } from '../mocks/mock-sync.storage'; -import { MockCookieService } from '../mocks/mock-cookie.service'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../helpers/mocks/service/mock-cookie.service'; import { CourseManagementService } from 'app/course/manage/course-management.service'; chai.use(sinonChai); @@ -87,7 +87,7 @@ describe('GuidedTourService', () => { describe('Service method', () => { let service: GuidedTourService; - let httpMock: any; + let httpMock: HttpTestingController; const expected = new GuidedTourSetting('guided_tour_key', 1, GuidedTourState.STARTED); beforeEach(() => { @@ -172,6 +172,7 @@ describe('GuidedTourService', () => { guidedTourComponent = guidedTourComponentFixture.componentInstance; const navBarComponentFixture = TestBed.createComponent(NavbarComponent); + // eslint-disable-next-line @typescript-eslint/no-unused-vars const navBarComponent = navBarComponentFixture.componentInstance; router = TestBed.inject(Router); @@ -187,7 +188,7 @@ describe('GuidedTourService', () => { }); }); - function prepareGuidedTour(tour: GuidedTour) { + function prepareGuidedTour(guidedTour: GuidedTour) { // Prepare GuidedTourService and GuidedTourComponent spyOn(guidedTourService, 'init').and.returnValue(of()); spyOn(guidedTourService, 'getLastSeenTourStepIndex').and.returnValue(0); @@ -195,13 +196,13 @@ describe('GuidedTourService', () => { spyOn(guidedTourService, 'checkTourState').and.returnValue(true); spyOn(guidedTourService, 'updateGuidedTourSettings').and.returnValue(of()); spyOn(guidedTourService, 'enableTour').and.callFake(() => { - guidedTourService['availableTourForComponent'] = tour; - guidedTourService.currentTour = tour; + guidedTourService['availableTourForComponent'] = guidedTour; + guidedTourService.currentTour = guidedTour; }); spyOn(guidedTourComponent, 'subscribeToDotChanges').and.callFake(() => {}); } - async function startCourseOverviewTour(tour: GuidedTour) { + async function startCourseOverviewTour(guidedTour: GuidedTour) { guidedTourComponent.ngAfterViewInit(); await guidedTourComponentFixture.ngZone!.run(() => { @@ -210,7 +211,7 @@ describe('GuidedTourService', () => { // Start course overview tour expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).to.not.exist; - guidedTourService['enableTour'](tour, true); + guidedTourService['enableTour'](guidedTour, true); guidedTourService['startTour'](); guidedTourComponentFixture.detectChanges(); expect(guidedTourComponentFixture.debugElement.query(By.css('.tour-step'))).to.exist; diff --git a/src/test/javascript/spec/service/ide-build-and-test-service.spec.ts b/src/test/javascript/spec/service/ide-build-and-test.service.spec.ts similarity index 92% rename from src/test/javascript/spec/service/ide-build-and-test-service.spec.ts rename to src/test/javascript/spec/service/ide-build-and-test.service.spec.ts index 3bda4ef5e39f..3087f48665d8 100644 --- a/src/test/javascript/spec/service/ide-build-and-test-service.spec.ts +++ b/src/test/javascript/spec/service/ide-build-and-test.service.spec.ts @@ -3,17 +3,17 @@ import * as sinonChai from 'sinon-chai'; import { IProgrammingSubmissionService } from 'app/exercises/programming/participate/programming-submission.service'; import { IParticipationWebsocketService } from 'app/overview/participation-websocket.service'; import { SinonSpy, SinonStub, spy, stub } from 'sinon'; -import { MockProgrammingSubmissionService } from '../mocks/mock-programming-submission.service'; +import { MockProgrammingSubmissionService } from '../helpers/mocks/service/mock-programming-submission.service'; import { Result } from 'app/entities/result.model'; import { BehaviorSubject, of } from 'rxjs'; import { Feedback } from 'app/entities/feedback.model'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { IBuildLogService } from 'app/exercises/programming/shared/service/build-log.service'; -import { MockParticipationWebsocketService } from '../mocks/mock-participation-websocket.service'; -import { MockCodeEditorBuildLogService } from '../mocks/mock-code-editor-build-log.service'; +import { MockParticipationWebsocketService } from '../helpers/mocks/service/mock-participation-websocket.service'; +import { MockCodeEditorBuildLogService } from '../helpers/mocks/service/mock-code-editor-build-log.service'; import { OrionBuildAndTestService } from 'app/shared/orion/orion-build-and-test.service'; import { OrionConnectorService } from 'app/shared/orion/orion-connector.service'; -import { MockOrionConnectorService } from '../mocks/mock-orion-connector.service'; +import { MockOrionConnectorService } from '../helpers/mocks/service/mock-orion-connector.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/service/login-service.spec.ts b/src/test/javascript/spec/service/login.service.spec.ts similarity index 87% rename from src/test/javascript/spec/service/login-service.spec.ts rename to src/test/javascript/spec/service/login.service.spec.ts index 3b3df41d6c64..f83c423da54d 100644 --- a/src/test/javascript/spec/service/login-service.spec.ts +++ b/src/test/javascript/spec/service/login.service.spec.ts @@ -2,16 +2,16 @@ import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; import { SinonStub, stub } from 'sinon'; import { of, throwError } from 'rxjs'; -import { MockWebsocketService } from '../mocks/mock-websocket.service'; -import { MockRouter } from '../mocks/mock-router.service'; -import { MockAccountService } from '../mocks/mock-account.service'; -import { MockAuthServerProviderService } from '../mocks/mock-auth-server-provider.service'; -import { MockAlertService } from '../mocks/mock-alert.service'; +import { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service'; +import { MockRouter } from '../helpers/mocks/mock-router'; +import { MockAccountService } from '../helpers/mocks/service/mock-account.service'; +import { MockAuthServerProviderService } from '../helpers/mocks/service/mock-auth-server-provider.service'; +import { MockAlertService } from '../helpers/mocks/service/mock-alert.service'; import { IAccountService } from 'app/core/auth/account.service'; import { IWebsocketService } from 'app/core/websocket/websocket.service'; import { LoginService } from 'app/core/login/login.service'; import { IAuthServerProvider } from 'app/core/auth/auth-jwt.service'; -import { MockNotificationService } from '../mocks/mock-notification.service'; +import { MockNotificationService } from '../helpers/mocks/service/mock-notification.service'; chai.use(sinonChai); const expect = chai.expect; diff --git a/src/test/javascript/spec/service/logs.service.spec.ts b/src/test/javascript/spec/service/logs.service.spec.ts new file mode 100644 index 000000000000..cb5ab300165b --- /dev/null +++ b/src/test/javascript/spec/service/logs.service.spec.ts @@ -0,0 +1,56 @@ +import { TestBed } from '@angular/core/testing'; + +import { LogsService } from 'app/admin/logs/logs.service'; +import { Log } from 'app/admin/logs/log.model'; +import { SERVER_API_URL } from 'app/app.constants'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +describe('Logs Service', () => { + let service: LogsService; + let httpMock; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + + service = TestBed.inject(LogsService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + describe('Service methods', () => { + it('should call correct URL', () => { + service.findAll().subscribe(() => {}); + + const req = httpMock.expectOne({ method: 'GET' }); + const resourceUrl = SERVER_API_URL + 'management/logs'; + expect(req.request.url).toEqual(resourceUrl); + }); + + it('should return Logs', () => { + const log = new Log('main', 'ERROR'); + + service.findAll().subscribe((received) => { + expect(received.body[0]).toEqual(log); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([log]); + }); + + it('should change log level', () => { + const log = new Log('main', 'ERROR'); + + service.changeLevel(log).subscribe((received) => { + expect(received.body[0]).toEqual(log); + }); + + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush([log]); + }); + }); +}); diff --git a/src/test/javascript/spec/service/markdown.service.spec.ts b/src/test/javascript/spec/service/markdown.service.spec.ts index 2d3d4f39232b..509a9f6548ac 100644 --- a/src/test/javascript/spec/service/markdown.service.spec.ts +++ b/src/test/javascript/spec/service/markdown.service.spec.ts @@ -8,7 +8,7 @@ chai.use(sinonChai); const expect = chai.expect; describe('Markdown Service', () => { - let artemisMarkdown = new ArtemisMarkdownService(); + const artemisMarkdown = new ArtemisMarkdownService(); const hintText = 'Add an explanation here (only visible in feedback after quiz has ended)'; const markdownHint = '[hint] ' + hintText; const explanationText = 'Add an explanation here (only visible in feedback after quiz has ended)'; diff --git a/src/test/javascript/spec/service/metrics.service.spec.ts b/src/test/javascript/spec/service/metrics.service.spec.ts new file mode 100644 index 000000000000..b0e4d3c68741 --- /dev/null +++ b/src/test/javascript/spec/service/metrics.service.spec.ts @@ -0,0 +1,55 @@ +import { TestBed } from '@angular/core/testing'; + +import { JhiMetricsService } from 'app/admin/metrics/metrics.service'; +import { SERVER_API_URL } from 'app/app.constants'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +describe('Logs Service', () => { + let service: JhiMetricsService; + let httpMock; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + + service = TestBed.inject(JhiMetricsService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + describe('Service methods', () => { + it('should call correct URL', () => { + service.getMetrics().subscribe(() => {}); + + const req = httpMock.expectOne({ method: 'GET' }); + const resourceUrl = SERVER_API_URL + 'management/jhimetrics'; + expect(req.request.url).toEqual(resourceUrl); + }); + + it('should return Metrics', () => { + const metrics = []; + + service.getMetrics().subscribe((received) => { + expect(received.body[0]).toEqual(metrics); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([metrics]); + }); + + it('should return Thread Dump', () => { + const dump = [{ name: 'test1', threadState: 'RUNNABLE' }]; + + service.threadDump().subscribe((received) => { + expect(received.body[0]).toEqual(dump); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush([dump]); + }); + }); +}); diff --git a/src/test/javascript/spec/service/modeling-exercise.service.spec.ts b/src/test/javascript/spec/service/modeling-exercise.service.spec.ts new file mode 100644 index 000000000000..bcd2bfcca430 --- /dev/null +++ b/src/test/javascript/spec/service/modeling-exercise.service.spec.ts @@ -0,0 +1,94 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { take } from 'rxjs/operators'; +import { ModelingExerciseService } from 'app/exercises/modeling/manage/modeling-exercise.service'; +import { DiagramType, ModelingExercise } from 'app/entities/modeling-exercise.model'; +import { TranslateService } from '@ngx-translate/core'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { routes } from 'app/exercises/modeling/manage/modeling-exercise.route'; +import { RouterTestingModule } from '@angular/router/testing'; +import { ArtemisModelingExerciseModule } from 'app/exercises/modeling/manage/modeling-exercise.module'; + +describe('ModelingExercise Service', () => { + let injector: TestBed; + let service: ModelingExerciseService; + let httpMock: HttpTestingController; + let elemDefault: ModelingExercise; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisModelingExerciseModule, HttpClientTestingModule, RouterTestingModule.withRoutes(routes)], + providers: [ + { provide: TranslateService, useClass: MockTranslateService }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + ], + }); + injector = getTestBed(); + service = injector.get(ModelingExerciseService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new ModelingExercise(DiagramType.ComponentDiagram); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a ModelingExercise', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new ModelingExercise(DiagramType.ComponentDiagram)) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a ModelingExercise', async () => { + const returnedFromService = Object.assign( + { + diagramType: 'BBBBBB', + sampleSolutionModel: 'BBBBBB', + sampleSolutionExplanation: 'BBBBBB', + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should delete a ModelingExercise', async () => { + service.delete(123).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/modeling-submission.service.spec.ts b/src/test/javascript/spec/service/modeling-submission.service.spec.ts new file mode 100644 index 000000000000..40ca7261a34d --- /dev/null +++ b/src/test/javascript/spec/service/modeling-submission.service.spec.ts @@ -0,0 +1,74 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { take } from 'rxjs/operators'; +import { ModelingSubmissionService } from 'app/exercises/modeling/participate/modeling-submission.service'; +import { ModelingSubmission } from 'app/entities/modeling-submission.model'; + +describe('ModelingSubmission Service', () => { + let injector: TestBed; + let service: ModelingSubmissionService; + let httpMock: HttpTestingController; + let elemDefault: ModelingSubmission; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + injector = getTestBed(); + service = injector.get(ModelingSubmissionService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new ModelingSubmission(); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .getSubmission(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a ModelingSubmission', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new ModelingSubmission(), 1) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a ModelingSubmission', async () => { + const returnedFromService = Object.assign( + { + model: 'BBBBBB', + explanationText: 'BBBBBB', + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected, 1) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/component/orion/orion-version-validator.service.spec.ts b/src/test/javascript/spec/service/orion-version-validator.service.spec.ts similarity index 93% rename from src/test/javascript/spec/component/orion/orion-version-validator.service.spec.ts rename to src/test/javascript/spec/service/orion-version-validator.service.spec.ts index 4a5055b4cd55..ece68e46ac13 100644 --- a/src/test/javascript/spec/component/orion/orion-version-validator.service.spec.ts +++ b/src/test/javascript/spec/service/orion-version-validator.service.spec.ts @@ -4,9 +4,9 @@ import { SinonSpy, SinonStub, spy, stub } from 'sinon'; import { OrionVersionValidator } from 'app/shared/orion/outdated-plugin-warning/orion-version-validator.service'; import { ProfileService } from 'app/shared/layouts/profiles/profile.service'; import { Router } from '@angular/router'; -import { MockProfileService } from '../../mocks/mock-profile.service'; -import { MockWindowRef } from '../../mocks/mock-window.service'; -import { MockRouter } from '../../mocks/mock-router.service'; +import { MockProfileService } from '../helpers/mocks/service/mock-profile.service'; +import { MockWindowRef } from '../helpers/mocks/service/mock-window.service'; +import { MockRouter } from '../helpers/mocks/mock-router'; import { of } from 'rxjs'; import { ProfileInfo } from 'app/shared/layouts/profiles/profile-info.model'; diff --git a/src/test/javascript/spec/service/participation-websocket-service.spec.ts b/src/test/javascript/spec/service/participation-websocket.service.spec.ts similarity index 97% rename from src/test/javascript/spec/service/participation-websocket-service.spec.ts rename to src/test/javascript/spec/service/participation-websocket.service.spec.ts index 619aa7d5c43e..bf8b3ade39a6 100644 --- a/src/test/javascript/spec/service/participation-websocket-service.spec.ts +++ b/src/test/javascript/spec/service/participation-websocket.service.spec.ts @@ -4,7 +4,7 @@ import { SinonSpy, SinonStub, spy, stub } from 'sinon'; import { BehaviorSubject, Subject } from 'rxjs'; import * as sinonChai from 'sinon-chai'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockWebsocketService } from '../mocks/mock-websocket.service'; +import { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service'; import { Participation } from 'app/entities/participation/participation.model'; import { Result } from 'app/entities/result.model'; import { IWebsocketService } from 'app/core/websocket/websocket.service'; @@ -14,10 +14,10 @@ const expect = chai.expect; describe('ParticipationWebsocketService', () => { let websocketService: IWebsocketService; - let receiveResultForParticipationSubject: Subject; let receiveParticipationSubject: Subject; - let receiveResultForParticipation2Subject: Subject; let receiveParticipation2Subject: Subject; + let receiveResultForParticipationSubject: Subject; + let receiveResultForParticipation2Subject: Subject; let subscribeSpy: SinonSpy; let receiveStub: SinonStub; let unsubscribeSpy: SinonSpy; @@ -169,8 +169,11 @@ describe('ParticipationWebsocketService', () => { expect(participationSpy).to.have.been.calledOnceWithExactly({ ...participation, results: [...participation.results, newRatedResult] }); }); + /* eslint-disable no-unused-vars */ it('should attach the result to participation if the participation has null for results value', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars const { results, ...participationWithoutResult } = participation; + participationWebsocketService.subscribeForLatestResultOfParticipation(participationWithoutResult.id); participationWebsocketService.addParticipation(participationWithoutResult as Participation); participationWebsocketService.subscribeForParticipationChanges(); @@ -190,4 +193,5 @@ describe('ParticipationWebsocketService', () => { expect(resultSpy).to.have.been.calledOnceWithExactly(newRatedResult); expect(participationSpy).to.have.been.calledOnceWithExactly({ ...participationWithoutResult, results: [newRatedResult] }); }); + /* eslint-enable no-unused-vars */ }); diff --git a/src/test/javascript/spec/service/participation.service.spec.ts b/src/test/javascript/spec/service/participation.service.spec.ts new file mode 100644 index 000000000000..207048dbef3b --- /dev/null +++ b/src/test/javascript/spec/service/participation.service.spec.ts @@ -0,0 +1,111 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { map, take } from 'rxjs/operators'; +import * as moment from 'moment'; +import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; +import { ParticipationService } from 'app/exercises/shared/participation/participation.service'; +import { Participation } from 'app/entities/participation/participation.model'; +import { StudentParticipation } from 'app/entities/participation/student-participation.model'; + +describe('Participation Service', () => { + let injector: TestBed; + let service: ParticipationService; + let httpMock: HttpTestingController; + let elemDefault: Participation; + let currentDate: moment.Moment; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + injector = getTestBed(); + service = injector.get(ParticipationService); + httpMock = injector.get(HttpTestingController); + currentDate = moment(); + + elemDefault = new StudentParticipation(); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign( + { + initializationDate: currentDate.format(DATE_TIME_FORMAT), + }, + elemDefault, + ); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a Participation', async () => { + const returnedFromService = Object.assign( + { + repositoryUrl: 'BBBBBB', + buildPlanId: 'BBBBBB', + initializationState: 'BBBBBB', + initializationDate: currentDate.format(DATE_TIME_FORMAT), + presentationScore: 1, + }, + elemDefault, + ); + + const expected = Object.assign( + { + initializationDate: currentDate, + }, + returnedFromService, + ); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of Participation', async () => { + const returnedFromService = Object.assign( + { + repositoryUrl: 'BBBBBB', + buildPlanId: 'BBBBBB', + initializationState: 'BBBBBB', + initializationDate: currentDate.format(DATE_TIME_FORMAT), + presentationScore: 1, + }, + elemDefault, + ); + const expected = Object.assign( + { + initializationDate: currentDate, + }, + returnedFromService, + ); + service + .findAllParticipationsByExercise(expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a Participation', async () => { + service.delete(123).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/programming-exercise-instruction-analysis-service.spec.ts b/src/test/javascript/spec/service/programming-exercise-instruction-analysis.service.spec.ts similarity index 93% rename from src/test/javascript/spec/service/programming-exercise-instruction-analysis-service.spec.ts rename to src/test/javascript/spec/service/programming-exercise-instruction-analysis.service.spec.ts index e2ec9fa20291..4e92a76fd1b4 100644 --- a/src/test/javascript/spec/service/programming-exercise-instruction-analysis-service.spec.ts +++ b/src/test/javascript/spec/service/programming-exercise-instruction-analysis.service.spec.ts @@ -1,5 +1,5 @@ -import { problemStatement } from '../sample/problemStatement.json'; -import { MockTranslateService } from '../mocks/mock-translate.service'; +import { problemStatement } from '../helpers/sample/problemStatement.json'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; import { ExerciseHint } from 'app/entities/exercise-hint.model'; import * as chai from 'chai'; import * as sinonChai from 'sinon-chai'; diff --git a/src/test/javascript/spec/service/programming-exercise-instruction-service.spec.ts b/src/test/javascript/spec/service/programming-exercise-instruction.service.spec.ts similarity index 100% rename from src/test/javascript/spec/service/programming-exercise-instruction-service.spec.ts rename to src/test/javascript/spec/service/programming-exercise-instruction.service.spec.ts diff --git a/src/test/javascript/spec/service/programming-exercise-test-case-service.spec.ts b/src/test/javascript/spec/service/programming-exercise-test-case.service.spec.ts similarity index 90% rename from src/test/javascript/spec/service/programming-exercise-test-case-service.spec.ts rename to src/test/javascript/spec/service/programming-exercise-test-case.service.spec.ts index ef11b99e2c57..45d7de269934 100644 --- a/src/test/javascript/spec/service/programming-exercise-test-case-service.spec.ts +++ b/src/test/javascript/spec/service/programming-exercise-test-case.service.spec.ts @@ -4,12 +4,11 @@ import { SinonSpy, SinonStub, spy, stub } from 'sinon'; import { of, Subject } from 'rxjs'; import { tap } from 'rxjs/operators'; import * as sinonChai from 'sinon-chai'; -import { MockWebsocketService } from '../mocks/mock-websocket.service'; +import { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service'; import { IWebsocketService } from 'app/core/websocket/websocket.service.ts'; import { ProgrammingExerciseTestCaseService } from 'app/exercises/programming/manage/services/programming-exercise-test-case.service'; -import { MockHttpService } from '../mocks/mock-http.service'; +import { MockHttpService } from '../helpers/mocks/service/mock-http.service'; import { ProgrammingExerciseTestCase } from 'app/entities/programming-exercise-test-case.model'; -import { Participation } from 'app/entities/participation/participation.model'; import { Result } from 'app/entities/result.model'; chai.use(sinonChai); @@ -19,9 +18,7 @@ describe('ProgrammingExerciseTestCaseService', () => { let websocketService: IWebsocketService; let httpService: MockHttpService; let exercise1TestCaseSubject: Subject; - let receiveParticipationSubject: Subject; let exercise2TestCaseSubject: Subject; - let receiveParticipation2Subject: Subject; let subscribeSpy: SinonSpy; let receiveStub: SinonStub; let unsubscribeSpy: SinonSpy; @@ -58,8 +55,6 @@ describe('ProgrammingExerciseTestCaseService', () => { exercise1TestCaseSubject = new Subject(); exercise2TestCaseSubject = new Subject(); - receiveParticipationSubject = new Subject(); - receiveParticipation2Subject = new Subject(); receiveStub.withArgs(exercise1Topic).returns(exercise1TestCaseSubject); receiveStub.withArgs(exercise2Topic).returns(exercise2TestCaseSubject); getStub.withArgs(`${testCaseService.testCaseUrl}/${exercise1.id}/test-cases`).returns(of(testCases1)); @@ -114,7 +109,7 @@ describe('ProgrammingExerciseTestCaseService', () => { }); it('should notify subscribers on new test case value', () => { - const newTestCases = testCases1.map((testCase) => ({ ...testCase, weight: 30 })); + const newTestCasesOracle = testCases1.map((testCase) => ({ ...testCase, weight: 30 })); let testCasesExercise1Subscriber1; let testCasesExercise1Subscriber2; // Subscriber 1. @@ -131,9 +126,9 @@ describe('ProgrammingExerciseTestCaseService', () => { expect(testCasesExercise1Subscriber1).to.equal(testCases1); expect(testCasesExercise1Subscriber2).to.equal(testCases1); - testCaseService.notifyTestCases(exercise1.id, newTestCases); + testCaseService.notifyTestCases(exercise1.id, newTestCasesOracle); - expect(testCasesExercise1Subscriber1).to.equal(newTestCases); - expect(testCasesExercise1Subscriber2).to.equal(newTestCases); + expect(testCasesExercise1Subscriber1).to.equal(newTestCasesOracle); + expect(testCasesExercise1Subscriber2).to.equal(newTestCasesOracle); }); }); diff --git a/src/test/javascript/spec/service/programming-exercise.service.spec.ts b/src/test/javascript/spec/service/programming-exercise.service.spec.ts new file mode 100644 index 000000000000..9ca5b25816d9 --- /dev/null +++ b/src/test/javascript/spec/service/programming-exercise.service.spec.ts @@ -0,0 +1,131 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { map, take } from 'rxjs/operators'; +import { ProgrammingExerciseService } from 'app/exercises/programming/manage/services/programming-exercise.service'; +import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; +import { TranslateService } from '@ngx-translate/core'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { routes } from 'app/exercises/programming/manage/programming-exercise-management-routing.module'; +import { RouterTestingModule } from '@angular/router/testing'; +import { ArtemisTestModule } from '../test.module'; +import { FormsModule } from '@angular/forms'; +import { ArtemisSharedModule } from 'app/shared/shared.module'; +import { ArtemisSharedComponentModule } from 'app/shared/components/shared-component.module'; +import { ArtemisProgrammingExerciseManagementModule } from 'app/exercises/programming/manage/programming-exercise-management.module'; + +describe('ProgrammingExercise Service', () => { + let injector: TestBed; + let service: ProgrammingExerciseService; + let httpMock: HttpTestingController; + let elemDefault: ProgrammingExercise; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ + HttpClientTestingModule, + RouterTestingModule.withRoutes(routes), + ArtemisTestModule, + FormsModule, + ArtemisSharedModule, + ArtemisSharedComponentModule, + ArtemisProgrammingExerciseManagementModule, + ], + providers: [ + { provide: TranslateService, useClass: MockTranslateService }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + ], + }); + injector = getTestBed(); + service = injector.get(ProgrammingExerciseService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new ProgrammingExercise(); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a ProgrammingExercise', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .automaticSetup(new ProgrammingExercise()) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a ProgrammingExercise', async () => { + const returnedFromService = Object.assign( + { + templateRepositoryUrl: 'BBBBBB', + solutionRepositoryUrl: 'BBBBBB', + templateBuildPlanId: 'BBBBBB', + publishBuildPlanUrl: true, + allowOnlineEditor: true, + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of ProgrammingExercise', async () => { + const returnedFromService = Object.assign( + { + templateRepositoryUrl: 'BBBBBB', + solutionRepositoryUrl: 'BBBBBB', + templateBuildPlanId: 'BBBBBB', + publishBuildPlanUrl: true, + allowOnlineEditor: true, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a ProgrammingExercise', async () => { + service.delete(123, false, false).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/programming-submission-service.spec.ts b/src/test/javascript/spec/service/programming-submission.service.spec.ts similarity index 97% rename from src/test/javascript/spec/service/programming-submission-service.spec.ts rename to src/test/javascript/spec/service/programming-submission.service.spec.ts index fb9ee526c442..421f2b3feedb 100644 --- a/src/test/javascript/spec/service/programming-submission-service.spec.ts +++ b/src/test/javascript/spec/service/programming-submission.service.spec.ts @@ -4,8 +4,8 @@ import { SinonStub, spy, stub } from 'sinon'; import { BehaviorSubject, of, Subject } from 'rxjs'; import { range as _range } from 'lodash'; import * as sinonChai from 'sinon-chai'; -import { MockWebsocketService } from '../mocks/mock-websocket.service'; -import { MockHttpService } from '../mocks/mock-http.service'; +import { MockWebsocketService } from '../helpers/mocks/service/mock-websocket.service'; +import { MockHttpService } from '../helpers/mocks/service/mock-http.service'; import { ExerciseSubmissionState, IProgrammingSubmissionService, @@ -14,13 +14,13 @@ import { ProgrammingSubmissionStateObj, } from 'app/exercises/programming/participate/programming-submission.service'; import { IParticipationWebsocketService } from 'app/overview/participation-websocket.service'; -import { MockAlertService } from '../mocks/mock-alert.service'; +import { MockAlertService } from '../helpers/mocks/service/mock-alert.service'; import { Result } from 'app/entities/result.model'; import { SERVER_API_URL } from 'app/app.constants'; import { ProgrammingSubmission } from 'app/entities/programming-submission.model'; import { Submission } from 'app/entities/submission.model'; import { StudentParticipation } from 'app/entities/participation/student-participation.model'; -import { MockParticipationWebsocketService } from '../mocks/mock-participation-websocket.service'; +import { MockParticipationWebsocketService } from '../helpers/mocks/service/mock-participation-websocket.service'; chai.use(sinonChai); const expect = chai.expect; @@ -82,7 +82,7 @@ describe('ProgrammingSubmissionService', () => { // @ts-ignore submissionService.submissionSubjects = { [participationId]: cachedSubject }; - const returnedObservable = submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10); + submissionService.getLatestPendingSubmissionByParticipationId(participationId, 10); expect(fetchLatestPendingSubmissionSpy).to.not.have.been.called; expect(setupWebsocketSubscriptionSpy).to.not.have.been.called; expect(subscribeForNewResultSpy).to.not.have.been.called; @@ -258,7 +258,7 @@ describe('ProgrammingSubmissionService', () => { expect(fetchLatestPendingSubmissionsByExerciseIdSpy).to.have.been.calledOnceWithExactly(exerciseId); expect(receivedSubmissionState).to.deep.equal(expectedSubmissionState); - let resultEta: number = -1; + let resultEta = -1; submissionService.getResultEtaInMs().subscribe((eta) => (resultEta = eta)); // With 340 submissions, the eta should now have increased. diff --git a/src/test/javascript/spec/service/quiz-exercise.service.spec.ts b/src/test/javascript/spec/service/quiz-exercise.service.spec.ts new file mode 100644 index 000000000000..8564269963dd --- /dev/null +++ b/src/test/javascript/spec/service/quiz-exercise.service.spec.ts @@ -0,0 +1,123 @@ +import { TranslateService } from '@ngx-translate/core'; +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { map, take } from 'rxjs/operators'; +import { SessionStorageService } from 'ngx-webstorage'; +import { QuizExerciseService } from 'app/exercises/quiz/manage/quiz-exercise.service'; +import { QuizExercise } from 'app/entities/quiz/quiz-exercise.model'; +import { Course } from 'app/entities/course.model'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { ArtemisTestModule } from '../test.module'; + +describe('QuizExercise Service', () => { + let injector: TestBed; + let service: QuizExerciseService; + let httpMock: HttpTestingController; + let elemDefault: QuizExercise; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [ArtemisTestModule, HttpClientTestingModule], + providers: [ + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: TranslateService, useClass: MockTranslateService }, + ], + }); + injector = getTestBed(); + service = injector.get(QuizExerciseService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new QuizExercise(new Course()); + }); + + describe('Service methods', async () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a QuizExercise', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new QuizExercise(null)) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a QuizExercise', async () => { + const returnedFromService = Object.assign( + { + description: 'BBBBBB', + explanation: 'BBBBBB', + randomizeQuestionOrder: true, + allowedNumberOfAttempts: 1, + isVisibleBeforeStart: true, + isOpenForPractice: true, + isPlannedToStart: true, + duration: 1, + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of QuizExercise', async () => { + const returnedFromService = Object.assign( + { + description: 'BBBBBB', + explanation: 'BBBBBB', + randomizeQuestionOrder: true, + allowedNumberOfAttempts: 1, + isVisibleBeforeStart: true, + isOpenForPractice: true, + isPlannedToStart: true, + duration: 1, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a QuizExercise', async () => { + service.delete(123).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/student-question-answer.service.spec.ts b/src/test/javascript/spec/service/student-question-answer.service.spec.ts new file mode 100644 index 000000000000..8b1bb3b5227b --- /dev/null +++ b/src/test/javascript/spec/service/student-question-answer.service.spec.ts @@ -0,0 +1,94 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpResponse } from '@angular/common/http'; +import * as chai from 'chai'; +import { take } from 'rxjs/operators'; +import { StudentQuestionAnswerService } from 'app/overview/student-questions/student-question-answer.service'; +import { StudentQuestionAnswer } from 'app/entities/student-question-answer.model'; + +const expect = chai.expect; + +describe('ExerciseHint Service', () => { + let injector: TestBed; + let service: StudentQuestionAnswerService; + let httpMock: HttpTestingController; + let elemDefault: StudentQuestionAnswer; + let expectedResult: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + expectedResult = {} as HttpResponse; + injector = getTestBed(); + service = injector.get(StudentQuestionAnswerService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new StudentQuestionAnswer(); + elemDefault.id = 0; + elemDefault.answerDate = null; + elemDefault.answerText = 'This is a test answer'; + }); + + describe('Service methods', () => { + it('should find a StudentQuestionAnswer', async () => { + const returnedFromService = { ...elemDefault }; + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(elemDefault); + }); + + it('should create a StudentQuestionAnswer', async () => { + const returnedFromService = { ...elemDefault, id: 0 }; + const expected = { ...returnedFromService }; + service + .create(new StudentQuestionAnswer()) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should update a StudentQuestionAnswer text field', async () => { + const returnedFromService = { ...elemDefault, answerText: 'This is another test answer' }; + const expected = { ...returnedFromService }; + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should update a StudentQuestionAnswer tutorApproved field', async () => { + const returnedFromService = { ...elemDefault, tutorApproved: true }; + const expected = { ...returnedFromService }; + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should delete a StudentQuestionAnswer', async () => { + service.delete(123).subscribe((resp) => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult).to.be.true; + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/student-question.service.spec.ts b/src/test/javascript/spec/service/student-question.service.spec.ts new file mode 100644 index 000000000000..fdeba820b88f --- /dev/null +++ b/src/test/javascript/spec/service/student-question.service.spec.ts @@ -0,0 +1,71 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { HttpResponse } from '@angular/common/http'; +import * as chai from 'chai'; +import { take } from 'rxjs/operators'; +import { StudentQuestionService } from 'app/overview/student-questions/student-question.service'; +import { StudentQuestion } from 'app/entities/student-question.model'; + +const expect = chai.expect; + +describe('ExerciseHint Service', () => { + let injector: TestBed; + let service: StudentQuestionService; + let httpMock: HttpTestingController; + let elemDefault: StudentQuestion; + let expectedResult: any; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + expectedResult = {} as HttpResponse; + injector = getTestBed(); + service = injector.get(StudentQuestionService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new StudentQuestion(); + elemDefault.id = 0; + elemDefault.creationDate = null; + elemDefault.questionText = 'This is a test question'; + }); + + describe('Service methods', () => { + it('should create a StudentQuestion', async () => { + const returnedFromService = { ...elemDefault, id: 0 }; + const expected = { ...returnedFromService }; + service + .create(new StudentQuestion()) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should update a StudentQuestion', async () => { + const returnedFromService = { ...elemDefault, questionText: 'This is another test question' }; + + const expected = { ...returnedFromService }; + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => (expectedResult = resp)); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(returnedFromService); + expect(expectedResult.body).to.deep.equal(expected); + }); + + it('should delete a StudentQuestion', async () => { + service.delete(123).subscribe((resp) => (expectedResult = resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + expect(expectedResult).to.be.true; + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/text-editor-service.spec.ts b/src/test/javascript/spec/service/text-editor.service.spec.ts similarity index 90% rename from src/test/javascript/spec/service/text-editor-service.spec.ts rename to src/test/javascript/spec/service/text-editor.service.spec.ts index 0b9efe92d2ef..582d3a429718 100644 --- a/src/test/javascript/spec/service/text-editor-service.spec.ts +++ b/src/test/javascript/spec/service/text-editor.service.spec.ts @@ -1,11 +1,11 @@ import { TextEditorService } from 'app/exercises/text/participate/text-editor.service'; -import { HttpClient, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http'; +import { HttpClient, HttpEvent, HttpHandler } from '@angular/common/http'; import { Observable } from 'rxjs'; import { Language } from 'app/entities/tutor-group.model'; class MockHttpHandler implements HttpHandler { - handle(req: HttpRequest): Observable> { + handle(): Observable> { return new Observable>(); } } @@ -30,7 +30,7 @@ describe('TextEditorService', () => { expect(textEditorService.predictLanguage(testString)).toBe(Language.ENGLISH); }); it('Can detect a long German text ', () => { - //copied from https://de.wikipedia.org/wiki/Bernd_Br%C3%BCgge + // copied from https://de.wikipedia.org/wiki/Bernd_Br%C3%BCgge const testString = 'Bernd Brügge ist ein deutscher Informatiker und Ordinarius für Angewandte Softwaretechnik' + @@ -42,7 +42,7 @@ describe('TextEditorService', () => { expect(textEditorService.predictLanguage(testString)).toBe(Language.GERMAN); }); it('Can detect a long English text ', () => { - //copied from https://en.wikipedia.org/wiki/Bernd_Bruegge + // copied from https://en.wikipedia.org/wiki/Bernd_Bruegge const testString = 'Bernd Bruegge (German: Bernd Brügge) (born 1951) is a German computer scientist,' + diff --git a/src/test/javascript/spec/service/text-exercise.service.spec.ts b/src/test/javascript/spec/service/text-exercise.service.spec.ts new file mode 100644 index 000000000000..aa6230dd3ed7 --- /dev/null +++ b/src/test/javascript/spec/service/text-exercise.service.spec.ts @@ -0,0 +1,112 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { map, take } from 'rxjs/operators'; +import { TextExerciseService } from 'app/exercises/text/manage/text-exercise/text-exercise.service'; +import { TextExercise } from 'app/entities/text-exercise.model'; +import { Course } from 'app/entities/course.model'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { TranslateService } from '@ngx-translate/core'; +import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; +import { Router } from '@angular/router'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { MockRouter } from '../helpers/mocks/mock-router'; + +describe('TextExercise Service', () => { + let injector: TestBed; + let service: TextExerciseService; + let httpMock: HttpTestingController; + let elemDefault: TextExercise; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [ + { provide: TranslateService, useClass: MockTranslateService }, + { provide: SessionStorageService, useClass: MockSyncStorage }, + { provide: Router, useClass: MockRouter }, + { provide: LocalStorageService, useClass: MockSyncStorage }, + ], + }); + injector = getTestBed(); + service = injector.get(TextExerciseService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new TextExercise(new Course()); + }); + + describe('Service methods', () => { + it('should find an element', async () => { + const returnedFromService = Object.assign({}, elemDefault); + service + .find(123) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: elemDefault })); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should create a TextExercise', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new TextExercise(null)) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a TextExercise', async () => { + const returnedFromService = Object.assign( + { + sampleSolution: 'BBBBBB', + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should return a list of TextExercise', async () => { + const returnedFromService = Object.assign( + { + sampleSolution: 'BBBBBB', + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .query(expected) + .pipe( + take(1), + map((resp) => resp.body), + ) + .subscribe((body) => expect(body).toContainEqual(expected)); + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(JSON.stringify([returnedFromService])); + httpMock.verify(); + }); + + it('should delete a TextExercise', async () => { + service.delete(123).subscribe((resp) => expect(resp.ok)); + + const req = httpMock.expectOne({ method: 'DELETE' }); + req.flush({ status: 200 }); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/text-submission.service.spec.ts b/src/test/javascript/spec/service/text-submission.service.spec.ts new file mode 100644 index 000000000000..dcdd5952ad5b --- /dev/null +++ b/src/test/javascript/spec/service/text-submission.service.spec.ts @@ -0,0 +1,61 @@ +import { getTestBed, TestBed } from '@angular/core/testing'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; +import { take } from 'rxjs/operators'; +import { TextSubmissionService } from 'app/exercises/text/participate/text-submission.service'; +import { TextSubmission } from 'app/entities/text-submission.model'; + +describe('TextSubmission Service', () => { + let injector: TestBed; + let service: TextSubmissionService; + let httpMock: HttpTestingController; + let elemDefault: TextSubmission; + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + }); + injector = getTestBed(); + service = injector.get(TextSubmissionService); + httpMock = injector.get(HttpTestingController); + + elemDefault = new TextSubmission(); + }); + + describe('Service methods', async () => { + it('should create a TextSubmission', async () => { + const returnedFromService = Object.assign( + { + id: 0, + }, + elemDefault, + ); + const expected = Object.assign({}, returnedFromService); + service + .create(new TextSubmission(null)) + .pipe(take(1)) + .subscribe((resp: any) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'POST' }); + req.flush(JSON.stringify(returnedFromService)); + }); + + it('should update a TextSubmission', async () => { + const returnedFromService = Object.assign( + { + text: 'BBBBBB', + }, + elemDefault, + ); + + const expected = Object.assign({}, returnedFromService); + service + .update(expected) + .pipe(take(1)) + .subscribe((resp: any) => expect(resp).toMatchObject({ body: expected })); + const req = httpMock.expectOne({ method: 'PUT' }); + req.flush(JSON.stringify(returnedFromService)); + }); + }); + + afterEach(() => { + httpMock.verify(); + }); +}); diff --git a/src/test/javascript/spec/service/user-route-access-service.spec.ts b/src/test/javascript/spec/service/user-route-access.service.spec.ts similarity index 82% rename from src/test/javascript/spec/service/user-route-access-service.spec.ts rename to src/test/javascript/spec/service/user-route-access.service.spec.ts index 177b975f8edb..c4baba7e489d 100644 --- a/src/test/javascript/spec/service/user-route-access-service.spec.ts +++ b/src/test/javascript/spec/service/user-route-access.service.spec.ts @@ -5,29 +5,30 @@ import { UserRouteAccessService } from 'app/core/auth/user-route-access-service' import { ActivatedRouteSnapshot, Route } from '@angular/router'; import { ArtemisTestModule } from '../test.module'; import { TranslateService } from '@ngx-translate/core'; -import { MockTranslateService } from '../mocks/mock-translate.service'; -import { MockSyncStorage } from '../mocks/mock-sync.storage'; -import { MockCookieService } from '../mocks/mock-cookie.service'; +import { MockTranslateService } from '../helpers/mocks/service/mock-translate.service'; +import { MockSyncStorage } from '../helpers/mocks/service/mock-sync-storage.service'; +import { MockCookieService } from '../helpers/mocks/service/mock-cookie.service'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from '../mocks/mock-account.service'; +import { MockAccountService } from '../helpers/mocks/service/mock-account.service'; import { RouterTestingModule } from '@angular/router/testing'; import { CookieService } from 'ngx-cookie-service'; import { DeviceDetectorService } from 'ngx-device-detector'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { Mutable } from '../helpers/mutable'; -import { mockedActivatedRouteSnapshot } from '../helpers/mock-activated-route-snapshot'; +import { mockedActivatedRouteSnapshot } from '../helpers/mocks/activated-route/mock-activated-route-snapshot'; import { CourseExerciseDetailsComponent } from 'app/overview/exercise-details/course-exercise-details.component'; chai.use(sinonChai); const expect = chai.expect; describe('UserRouteAccessService', () => { + // eslint-disable-next-line @typescript-eslint/no-unused-vars let comp: CourseExerciseDetailsComponent; + const routeStateMock: any = { snapshot: {}, url: '/' }; + const route = 'courses/:courseId/exercises/:exerciseId'; let fixture: ComponentFixture; let service: UserRouteAccessService; - let routeStateMock: any = { snapshot: {}, url: '/' }; - let route = 'courses/:courseId/exercises/:exerciseId'; beforeEach(async(() => { TestBed.configureTestingModule({ diff --git a/src/test/javascript/spec/service/user.service.spec.ts b/src/test/javascript/spec/service/user.service.spec.ts new file mode 100644 index 000000000000..b8c5179920a8 --- /dev/null +++ b/src/test/javascript/spec/service/user.service.spec.ts @@ -0,0 +1,65 @@ +import { TestBed } from '@angular/core/testing'; +import { JhiDateUtils } from 'ng-jhipster'; + +import { User } from 'app/core/user/user.model'; +import { UserService } from 'app/core/user/user.service'; +import { SERVER_API_URL } from 'app/app.constants'; +import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; + +describe('User Service', () => { + let service: UserService; + let httpMock; + + beforeEach(() => { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [JhiDateUtils], + }); + + service = TestBed.inject(UserService); + httpMock = TestBed.inject(HttpTestingController); + }); + + afterEach(() => { + httpMock.verify(); + }); + + describe('Service methods', () => { + it('should call correct URL', () => { + service.find('user').subscribe(() => {}); + + const req = httpMock.expectOne({ method: 'GET' }); + const resourceUrl = SERVER_API_URL + 'api/users'; + expect(req.request.url).toEqual(`${resourceUrl}/user`); + }); + it('should return User', () => { + service.find('user').subscribe((received) => { + expect(received.body.login).toEqual('user'); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush(new User(1, 'user')); + }); + + it('should return Authorities', () => { + service.authorities().subscribe((_authorities) => { + expect(_authorities).toEqual(['ROLE_USER', 'ROLE_ADMIN']); + }); + const req = httpMock.expectOne({ method: 'GET' }); + + req.flush(['ROLE_USER', 'ROLE_ADMIN']); + }); + + it('should propagate not found response', () => { + service.find('user').subscribe(null, (_error: any) => { + expect(_error.status).toEqual(404); + }); + + const req = httpMock.expectOne({ method: 'GET' }); + req.flush('Invalid request parameters', { + status: 404, + statusText: 'Bad Request', + }); + }); + }); +}); diff --git a/src/test/javascript/spec/test.module.ts b/src/test/javascript/spec/test.module.ts index 78760642f531..5ac5bbce1990 100644 --- a/src/test/javascript/spec/test.module.ts +++ b/src/test/javascript/spec/test.module.ts @@ -3,15 +3,16 @@ import { ActivatedRoute, Router } from '@angular/router'; import { ElementRef, NgModule, Renderer2 } from '@angular/core'; import { HttpClientTestingModule } from '@angular/common/http/testing'; import { NgbActiveModal, NgbModal, NgbDatepickerConfig } from '@ng-bootstrap/ng-bootstrap'; -import { AlertService, JhiDataUtils, JhiDateUtils, JhiEventManager, JhiLanguageService, JhiParseLinks } from 'ng-jhipster'; +import { JhiAlertService, JhiDataUtils, JhiDateUtils, JhiEventManager, JhiLanguageService, JhiParseLinks } from 'ng-jhipster'; -import { MockLanguageHelper, MockLanguageService } from './helpers/mock-language.service'; +import { MockLanguageHelper, MockLanguageService } from './helpers/mocks/service/mock-language.service'; import { JhiLanguageHelper } from 'app/core/language/language.helper'; import { AccountService } from 'app/core/auth/account.service'; -import { MockAccountService } from './helpers/mock-account.service'; -import { MockActivatedRoute, MockRouter } from './helpers/mock-route.service'; -import { MockActiveModal } from './helpers/mock-active-modal.service'; -import { MockEventManager } from './helpers/mock-event-manager.service'; +import { MockAccountService } from './helpers/mocks/service/mock-account.service'; +import { MockActivatedRoute } from './helpers/mocks/activated-route/mock-activated-route'; +import { MockRouter } from './helpers/mocks/mock-router'; +import { MockActiveModal } from './helpers/mocks/service/mock-active-modal.service'; +import { MockEventManager } from './helpers/mocks/service/mock-event-manager.service'; import { CookieService } from 'ngx-cookie-service'; import { FaIconLibrary, FontAwesomeModule, FaIconComponent } from '@fortawesome/angular-fontawesome'; import { fas } from '@fortawesome/free-solid-svg-icons'; @@ -65,7 +66,7 @@ import { MockComponent } from 'ng-mocks'; useValue: null, }, { - provide: AlertService, + provide: JhiAlertService, useValue: null, }, { diff --git a/src/test/k6/ArtemisLogin.js b/src/test/k6/ArtemisLogin.js index 216f7636a459..c8b97baff8c2 100644 --- a/src/test/k6/ArtemisLogin.js +++ b/src/test/k6/ArtemisLogin.js @@ -1,437 +1,452 @@ import { group, sleep } from 'k6'; import http from 'k6/http'; import ws from 'k6/ws'; -import { Trend } from "k6/metrics"; +import { Trend } from 'k6/metrics'; // Version: 1.1 // Creator: Firefox // Browser: Firefox -var rest_call_metrics = new Trend("rest_call_metrics"); +var rest_call_metrics = new Trend('rest_call_metrics'); export let options = { maxRedirects: 0, ext: { - "loadimpact": { - "distribution": { - "load_zone0": { - "loadZone": "amazon:de:frankfurt", - "percent": 100 - } - } - } + loadimpact: { + distribution: { + load_zone0: { + loadZone: 'amazon:de:frankfurt', + percent: 100, + }, + }, + }, }, stages: [ { - "duration": "15s", - "target": 10 + duration: '15s', + target: 10, }, { - "duration": "15s", - "target": 20 + duration: '15s', + target: 20, }, { - "duration": "15s", - "target": 30 + duration: '15s', + target: 30, }, { - "duration": "15s", - "target": 40 + duration: '15s', + target: 40, }, { - "duration": "15s", - "target": 50 + duration: '15s', + target: 50, }, { - "duration": "15s", - "target": 60 + duration: '15s', + target: 60, }, { - "duration": "15s", - "target": 70 + duration: '15s', + target: 70, }, { - "duration": "15s", - "target": 80 + duration: '15s', + target: 80, }, { - "duration": "15s", - "target": 90 + duration: '15s', + target: 90, }, { - "duration": "180s", - "target": 100 - } + duration: '180s', + target: 100, + }, ], - vus: 100 + vus: 100, }; -export default function() { - let defaultXSRFToken = "42d141b5-9e1c-4390-ae06-5143753b4459"; - let protocol = "http"; // https or http - let websocketProtocol = "ws"; // wss if https is used; ws if http is used - let host = "nginx:80"; // host including port if differing from 80 (http) or 443 (https) - let baseUrl = protocol + "://" + host; - - let maxTestUser = 100; // the userId will be an integer between 1 and this number - - let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password - let websocketConnectionTime = 100; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished - - let userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"; - let acceptLanguage = "en-CA,en-US;q=0.7,en;q=0.3"; - let acceptEncoding = "gzip, deflate, br"; - - let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser - let password = "__ENV.BASE_PASSWORD"; // USERID gets replaced with a random number between 1 and maxTestUser - - group("Artemis Login", function() { - let req, res; - var total_waiting_time = 0; - - // The website is loaded initialy - req = [{ - "method": "get", - "url": baseUrl + "/#/", - "params": { - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Connection": "keep-alive", - "Upgrade-Insecure-Requests": "1", - "Pragma": "no-cache", - "Cache-Control": "no-cache" - }, - "tags": {"name": baseUrl + "/#/"} - } - } - ]; - res = http.batch(req); - for (var i = 0; i < req.length; i++) { - total_waiting_time += res[i].timings.waiting; - } - - // The dynamically generated links to the .css and .js files get extracted from the first response and a request is sent to every of these files - req = []; - // Add css/js files dynamically - let regex = /(?:"([^"]*\.(css|js))")/g; - var matched; - while((matched = regex.exec(res[0].body)) != undefined) { - req.push({ - "method": "get", - "url": baseUrl + "/" + matched[1], - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "*/*;q=0.1", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/dynamic-files"} - } - }); - } - res = http.batch(req); - for (var i = 0; i < req.length; i++) { - total_waiting_time += res[i].timings.waiting; - } - - // The favicon, the translations, some management information and the TUM logo is downloaded next - req = [{ - "method": "get", - "url": baseUrl + "/public/images/favicon.ico", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "image/webp,*/*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/favicon"} - } - },{ - "method": "get", - "url": baseUrl + "/i18n/en.json?buildTimestamp=1556135702468", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/i18n"} - } - },{ - "method": "get", - "url": baseUrl + "/management/info", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/management/info"} - } - },{ - "method": "get", - "url": baseUrl + "/api/account", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/account"} - } - },{ - "method": "get", - "url": baseUrl + "/content/7c761975dc7a3abfc710400d4dd51933.png", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "image/webp,*/*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/content"} - } - }]; - res = http.batch(req); - for (var i = 0; i < req.length; i++) { - total_waiting_time += res[i].timings.waiting; - } - - - // Now the user should type his login credentials, therefor we wait some time - sleep(delayBeforeLogin); - - // The user is randomly selected - let userId = Math.floor((Math.random() * maxTestUser)) + 1; - let currentUsername = username.replace("USERID", userId); - let currentPassword = password.replace("USERID", userId); - - // The user logs in; the authToken gets saved as we need it later - req = [{ - "method": "post", - "url": baseUrl + "/api/authenticate", - "body": "{\"username\":\"" + currentUsername + "\",\"password\":\"" + currentPassword +"\",\"rememberMe\":true}", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "X-XSRF-TOKEN": defaultXSRFToken, - "Content-Type": "application/json", - "Content-Length": "74", - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/authenticate"} - } - }]; - res = http.batch(req); - for (var i = 0; i < req.length; i++) { - total_waiting_time += res[i].timings.waiting; - } - let authToken = JSON.parse(res[0].body).id_token; - - // The user requests it own information of the account - req = [{ - "method": "get", - "url": baseUrl + "/api/account", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/account"} - } - }]; - - res = http.batch(req); - for (var i = 0; i < req.length; i++) { - total_waiting_time += res[i].timings.waiting; - } - - // A new XSRF Token is needed now, we have to extract it from the cookies - let xsrftoken = res[0].headers["Set-Cookie"].match('XSRF-TOKEN=(.*); path=\/(; secure)?')[1]; - - // Extract user as we need it for some websocket information - let user = JSON.parse(res[0].body); - - // Some more calls (dashboard, notification, courses to register) are made - req = [{ - "method": "get", - "url": baseUrl + "/api/courses/for-dashboard", - "params": { - "cookies": { - "XSRF-TOKEN": xsrftoken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/courses/for-dashboard"} - } - },{ - "method": "get", - "url": baseUrl + "/api/notifications/for-user", - "params": { - "cookies": { - "XSRF-TOKEN": xsrftoken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/notifications/for-user"} - } - }]; - res = http.batch(req); - for (var i = 0; i < req.length; i++) { - total_waiting_time += res[i].timings.waiting; - } - rest_call_metrics.add(total_waiting_time); - - let courses = JSON.parse(res[1].body); +export default function () { + let defaultXSRFToken = '42d141b5-9e1c-4390-ae06-5143753b4459'; + let protocol = 'http'; // https or http + let websocketProtocol = 'ws'; // wss if https is used; ws if http is used + let host = 'nginx:80'; // host including port if differing from 80 (http) or 443 (https) + let baseUrl = protocol + '://' + host; + + let maxTestUser = 100; // the userId will be an integer between 1 and this number + + let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password + let websocketConnectionTime = 100; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished + + let userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0'; + let acceptLanguage = 'en-CA,en-US;q=0.7,en;q=0.3'; + let acceptEncoding = 'gzip, deflate, br'; + + let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser + let password = '__ENV.BASE_PASSWORD'; // USERID gets replaced with a random number between 1 and maxTestUser + + group('Artemis Login', function () { + let req, res; + var total_waiting_time = 0; + + // The website is loaded initialy + req = [ + { + method: 'get', + url: baseUrl + '/#/', + params: { + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Connection: 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + }, + tags: { name: baseUrl + '/#/' }, + }, + }, + ]; + res = http.batch(req); + for (var i = 0; i < req.length; i++) { + total_waiting_time += res[i].timings.waiting; + } - // Initiate websocket connection if connection time is set to value greater than 0 - if (websocketConnectionTime > 0) { - let websocketEndpoint = websocketProtocol + "://" + host + "/websocket/tracker/websocket"; - let websocketUrl = websocketEndpoint + "?access_token=" + authToken; + // The dynamically generated links to the .css and .js files get extracted from the first response and a request is sent to every of these files + req = []; + // Add css/js files dynamically + let regex = /(?:"([^"]*\.(css|js))")/g; + var matched; + while ((matched = regex.exec(res[0].body)) != undefined) { + req.push({ + method: 'get', + url: baseUrl + '/' + matched[1], + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: '*/*;q=0.1', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/dynamic-files' }, + }, + }); + } + res = http.batch(req); + for (var i = 0; i < req.length; i++) { + total_waiting_time += res[i].timings.waiting; + } - var response = ws.connect(websocketUrl, {"tags": {"name": websocketEndpoint}}, function(socket) { - socket.on('open', function open() { - socket.send("CONNECT\nX-XSRF-TOKEN:" + xsrftoken + "\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000"); - }); + // The favicon, the translations, some management information and the TUM logo is downloaded next + req = [ + { + method: 'get', + url: baseUrl + '/public/images/favicon.ico', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'image/webp,*/*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/favicon' }, + }, + }, + { + method: 'get', + url: baseUrl + '/i18n/en.json?buildTimestamp=1556135702468', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/i18n' }, + }, + }, + { + method: 'get', + url: baseUrl + '/management/info', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/management/info' }, + }, + }, + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, + }, + }, + { + method: 'get', + url: baseUrl + '/content/7c761975dc7a3abfc710400d4dd51933.png', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'image/webp,*/*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/content' }, + }, + }, + ]; + res = http.batch(req); + for (var i = 0; i < req.length; i++) { + total_waiting_time += res[i].timings.waiting; + } - function getSubscriptionId() { - return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 12); + // Now the user should type his login credentials, therefor we wait some time + sleep(delayBeforeLogin); + + // The user is randomly selected + let userId = Math.floor(Math.random() * maxTestUser) + 1; + let currentUsername = username.replace('USERID', userId); + let currentPassword = password.replace('USERID', userId); + + // The user logs in; the authToken gets saved as we need it later + req = [ + { + method: 'post', + url: baseUrl + '/api/authenticate', + body: '{"username":"' + currentUsername + '","password":"' + currentPassword + '","rememberMe":true}', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + 'X-XSRF-TOKEN': defaultXSRFToken, + 'Content-Type': 'application/json', + 'Content-Length': '74', + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/authenticate' }, + }, + }, + ]; + res = http.batch(req); + for (var i = 0; i < req.length; i++) { + total_waiting_time += res[i].timings.waiting; + } + let authToken = JSON.parse(res[0].body).id_token; + + // The user requests it own information of the account + req = [ + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, + }, + }, + ]; + + res = http.batch(req); + for (var i = 0; i < req.length; i++) { + total_waiting_time += res[i].timings.waiting; } - function subscribeCourse(courseId, role) { - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/course/" + courseId + "/" + role +"\n\n\u0000"); + // A new XSRF Token is needed now, we have to extract it from the cookies + let xsrftoken = res[0].headers['Set-Cookie'].match('XSRF-TOKEN=(.*); path=/(; secure)?')[1]; + + // Extract user as we need it for some websocket information + let user = JSON.parse(res[0].body); + + // Some more calls (dashboard, notification, courses to register) are made + req = [ + { + method: 'get', + url: baseUrl + '/api/courses/for-dashboard', + params: { + cookies: { + 'XSRF-TOKEN': xsrftoken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/courses/for-dashboard' }, + }, + }, + { + method: 'get', + url: baseUrl + '/api/notifications/for-user', + params: { + cookies: { + 'XSRF-TOKEN': xsrftoken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/notifications/for-user' }, + }, + }, + ]; + res = http.batch(req); + for (var i = 0; i < req.length; i++) { + total_waiting_time += res[i].timings.waiting; } + rest_call_metrics.add(total_waiting_time); - socket.setInterval(function timeout() { - socket.ping(); - // console.log("Pinging every 10sec (setInterval test)"); - }, 10000); + let courses = JSON.parse(res[1].body); - // Send destination and subscription after 1 second - socket.setTimeout(function() { - socket.send("SEND\ndestination:/topic/activity\ncontent-length:20\n\n{\"page\":\"/overview\"}\u0000"); + // Initiate websocket connection if connection time is set to value greater than 0 + if (websocketConnectionTime > 0) { + let websocketEndpoint = websocketProtocol + '://' + host + '/websocket/tracker/websocket'; + let websocketUrl = websocketEndpoint + '?access_token=' + authToken; - courses.forEach(function(course) { - if (user.groups.includes(course.studentGroupName)) { - subscribeCourse(course.id, "STUDENT"); - } - if (user.groups.includes(course.teachingAssistantGroupName)) { - subscribeCourse(course.id, "TA"); - } - if (user.groups.includes(course.instructorGroupName)) { - subscribeCourse(course.id, "INSTRUCTOR"); - } + var response = ws.connect(websocketUrl, { tags: { name: websocketEndpoint } }, function (socket) { + socket.on('open', function open() { + socket.send('CONNECT\nX-XSRF-TOKEN:' + xsrftoken + '\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000'); + }); - // Subscribe for system and user notifications - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/system-notification\n\n\u0000"); - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/user/" + user.id + "/notifications\n\n\u0000"); - }); - }, 1 * 1000); + function getSubscriptionId() { + return Math.random() + .toString(36) + .replace(/[^a-z]+/g, '') + .substr(0, 12); + } - socket.setTimeout(function() { - socket.close(); - }, websocketConnectionTime * 1000); - }); - } - }); + function subscribeCourse(courseId, role) { + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/course/' + courseId + '/' + role + '\n\n\u0000'); + } + socket.setInterval(function timeout() { + socket.ping(); + // console.log("Pinging every 10sec (setInterval test)"); + }, 10000); + + // Send destination and subscription after 1 second + socket.setTimeout(function () { + socket.send('SEND\ndestination:/topic/activity\ncontent-length:20\n\n{"page":"/overview"}\u0000'); + + courses.forEach(function (course) { + if (user.groups.includes(course.studentGroupName)) { + subscribeCourse(course.id, 'STUDENT'); + } + if (user.groups.includes(course.teachingAssistantGroupName)) { + subscribeCourse(course.id, 'TA'); + } + if (user.groups.includes(course.instructorGroupName)) { + subscribeCourse(course.id, 'INSTRUCTOR'); + } + + // Subscribe for system and user notifications + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/system-notification\n\n\u0000'); + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/user/' + user.id + '/notifications\n\n\u0000'); + }); + }, 1 * 1000); + + socket.setTimeout(function () { + socket.close(); + }, websocketConnectionTime * 1000); + }); + } + }); } diff --git a/src/test/k6/ArtemisLoginNoJS.js b/src/test/k6/ArtemisLoginNoJS.js index d1a00c4382ab..5ad015870a8c 100644 --- a/src/test/k6/ArtemisLoginNoJS.js +++ b/src/test/k6/ArtemisLoginNoJS.js @@ -9,310 +9,323 @@ import ws from 'k6/ws'; export let options = { maxRedirects: 0, ext: { - "loadimpact": { - "distribution": { - "load_zone0": { - "loadZone": "amazon:de:frankfurt", - "percent": 100 - } - } - } + loadimpact: { + distribution: { + load_zone0: { + loadZone: 'amazon:de:frankfurt', + percent: 100, + }, + }, + }, }, stages: [ { - "duration": "5s", - "target": 30 + duration: '5s', + target: 30, }, { - "duration": "5s", - "target": 50 + duration: '5s', + target: 50, }, { - "duration": "5s", - "target": 80 + duration: '5s', + target: 80, }, { - "duration": "300s", - "target": 100 - } + duration: '300s', + target: 100, + }, ], - vus: 100 + vus: 100, }; -export default function() { - let defaultXSRFToken = "42d141b5-9e1c-4390-ae06-5143753b4459"; - let protocol = "https"; // https or http - let websocketProtocol = "wss"; // wss if https is used; ws if http is used - let host = "artemis.ase.in.tum.de"; // host including port if differing from 80 (http) or 443 (https) - let baseUrl = protocol + "://" + host; - - let maxTestUser = 100; // the userId will be an integer between 1 and this number +export default function () { + let defaultXSRFToken = '42d141b5-9e1c-4390-ae06-5143753b4459'; + let protocol = 'https'; // https or http + let websocketProtocol = 'wss'; // wss if https is used; ws if http is used + let host = 'artemis.ase.in.tum.de'; // host including port if differing from 80 (http) or 443 (https) + let baseUrl = protocol + '://' + host; - let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password - let websocketConnectionTime = 300; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished + let maxTestUser = 100; // the userId will be an integer between 1 and this number - let userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"; - let acceptLanguage = "en-CA,en-US;q=0.7,en;q=0.3"; - let acceptEncoding = "gzip, deflate, br"; + let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password + let websocketConnectionTime = 300; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished - let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser - let password = "__ENV.BASE_PASSWORD"; // USERID gets replaced with a random number between 1 and maxTestUser + let userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0'; + let acceptLanguage = 'en-CA,en-US;q=0.7,en;q=0.3'; + let acceptEncoding = 'gzip, deflate, br'; - group("Artemis Login", function() { - let req, res; + let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser + let password = '__ENV.BASE_PASSWORD'; // USERID gets replaced with a random number between 1 and maxTestUser - // The website is loaded initialy - req = [{ - "method": "get", - "url": baseUrl + "/#/", - "params": { - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Connection": "keep-alive", - "Upgrade-Insecure-Requests": "1", - "Pragma": "no-cache", - "Cache-Control": "no-cache" - }, - "tags": {"name": baseUrl + "/#/"} - } - } - ]; - res = http.batch(req); + group('Artemis Login', function () { + let req, res; - // The favicon, the translations, some management information and the TUM logo is downloaded next - req = [{ - "method": "get", - "url": baseUrl + "/i18n/en.json?buildTimestamp=1556135702468", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/i18n"} - } - },{ - "method": "get", - "url": baseUrl + "/management/info", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/management/info"} - } - },{ - "method": "get", - "url": baseUrl + "/api/account", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Connection": "keep-alive", - "Pragma": "no-cache", - "Cache-Control": "no-cache", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/account"} - } - }]; - res = http.batch(req); + // The website is loaded initialy + req = [ + { + method: 'get', + url: baseUrl + '/#/', + params: { + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Connection: 'keep-alive', + 'Upgrade-Insecure-Requests': '1', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + }, + tags: { name: baseUrl + '/#/' }, + }, + }, + ]; + res = http.batch(req); + // The favicon, the translations, some management information and the TUM logo is downloaded next + req = [ + { + method: 'get', + url: baseUrl + '/i18n/en.json?buildTimestamp=1556135702468', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/i18n' }, + }, + }, + { + method: 'get', + url: baseUrl + '/management/info', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/management/info' }, + }, + }, + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Connection: 'keep-alive', + Pragma: 'no-cache', + 'Cache-Control': 'no-cache', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, + }, + }, + ]; + res = http.batch(req); - // Now the user should type his login credentials, therefor we wait some time - sleep(delayBeforeLogin); + // Now the user should type his login credentials, therefor we wait some time + sleep(delayBeforeLogin); - // The user is randomly selected - let userId = Math.floor((Math.random() * maxTestUser)) + 1; - let currentUsername = username.replace("USERID", userId); - let currentPassword = password.replace("USERID", userId); + // The user is randomly selected + let userId = Math.floor(Math.random() * maxTestUser) + 1; + let currentUsername = username.replace('USERID', userId); + let currentPassword = password.replace('USERID', userId); - // The user logs in; the authToken gets saved as we need it later - req = [{ - "method": "post", - "url": baseUrl + "/api/authenticate", - "body": "{\"username\":\"" + currentUsername + "\",\"password\":\"" + currentPassword +"\",\"rememberMe\":true}", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "X-XSRF-TOKEN": defaultXSRFToken, - "Content-Type": "application/json", - "Content-Length": "74", - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/authenticate"} - } - }]; - res = http.batch(req); - let authToken = JSON.parse(res[0].body).id_token; + // The user logs in; the authToken gets saved as we need it later + req = [ + { + method: 'post', + url: baseUrl + '/api/authenticate', + body: '{"username":"' + currentUsername + '","password":"' + currentPassword + '","rememberMe":true}', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + 'X-XSRF-TOKEN': defaultXSRFToken, + 'Content-Type': 'application/json', + 'Content-Length': '74', + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/authenticate' }, + }, + }, + ]; + res = http.batch(req); + let authToken = JSON.parse(res[0].body).id_token; - // The user requests it own information of the account - req = [{ - "method": "get", - "url": baseUrl + "/api/account", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/account"} - } - }]; + // The user requests it own information of the account + req = [ + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, + }, + }, + ]; - res = http.batch(req); + res = http.batch(req); - // A new XSRF Token is needed now, we have to extract it from the cookies - let xsrftoken = res[0].headers["Set-Cookie"].match('XSRF-TOKEN=(.*); path=\/(; secure)?')[1]; + // A new XSRF Token is needed now, we have to extract it from the cookies + let xsrftoken = res[0].headers['Set-Cookie'].match('XSRF-TOKEN=(.*); path=/(; secure)?')[1]; - // Extract user as we need it for some websocket information - let user = JSON.parse(res[0].body); + // Extract user as we need it for some websocket information + let user = JSON.parse(res[0].body); - // Some more calls (dashboard, notification, courses to register) are made - req = [{ - "method": "get", - "url": baseUrl + "/api/courses/for-dashboard", - "params": { - "cookies": { - "XSRF-TOKEN": xsrftoken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/courses/for-dashboard"} - } - },{ - "method": "get", - "url": baseUrl + "/api/notifications/for-user", - "params": { - "cookies": { - "XSRF-TOKEN": xsrftoken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/notifications/for-user"} - } - }]; - res = http.batch(req); + // Some more calls (dashboard, notification, courses to register) are made + req = [ + { + method: 'get', + url: baseUrl + '/api/courses/for-dashboard', + params: { + cookies: { + 'XSRF-TOKEN': xsrftoken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/courses/for-dashboard' }, + }, + }, + { + method: 'get', + url: baseUrl + '/api/notifications/for-user', + params: { + cookies: { + 'XSRF-TOKEN': xsrftoken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/notifications/for-user' }, + }, + }, + ]; + res = http.batch(req); - let courses = JSON.parse(res[1].body); + let courses = JSON.parse(res[1].body); - // Initiate websocket connection if connection time is set to value greater than 0 - if (websocketConnectionTime > 0) { - let websocketEndpoint = websocketProtocol + "://" + host + "/websocket/tracker/websocket"; - let websocketUrl = websocketEndpoint + "?access_token=" + authToken; + // Initiate websocket connection if connection time is set to value greater than 0 + if (websocketConnectionTime > 0) { + let websocketEndpoint = websocketProtocol + '://' + host + '/websocket/tracker/websocket'; + let websocketUrl = websocketEndpoint + '?access_token=' + authToken; - var response = ws.connect(websocketUrl, {"tags": {"name": websocketEndpoint}}, function(socket) { - socket.on('open', function open() { - socket.send("CONNECT\nX-XSRF-TOKEN:" + xsrftoken + "\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000"); - }); + var response = ws.connect(websocketUrl, { tags: { name: websocketEndpoint } }, function (socket) { + socket.on('open', function open() { + socket.send('CONNECT\nX-XSRF-TOKEN:' + xsrftoken + '\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000'); + }); - function getSubscriptionId() { - return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 12); - } - - function subscribeCourse(courseId, role) { - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/course/" + courseId + "/" + role +"\n\n\u0000"); - } + function getSubscriptionId() { + return Math.random() + .toString(36) + .replace(/[^a-z]+/g, '') + .substr(0, 12); + } - socket.setInterval(function timeout() { - socket.ping(); - // console.log("Pinging every 10sec (setInterval test)"); - }, 10000); + function subscribeCourse(courseId, role) { + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/course/' + courseId + '/' + role + '\n\n\u0000'); + } - // Send destination and subscription after 1 second - socket.setTimeout(function() { - socket.send("SEND\ndestination:/topic/activity\ncontent-length:20\n\n{\"page\":\"/overview\"}\u0000"); + socket.setInterval(function timeout() { + socket.ping(); + // console.log("Pinging every 10sec (setInterval test)"); + }, 10000); - courses.forEach(function(course) { - if (user.groups.includes(course.studentGroupName)) { - subscribeCourse(course.id, "STUDENT"); - } - if (user.groups.includes(course.teachingAssistantGroupName)) { - subscribeCourse(course.id, "TA"); - } - if (user.groups.includes(course.instructorGroupName)) { - subscribeCourse(course.id, "INSTRUCTOR"); - } + // Send destination and subscription after 1 second + socket.setTimeout(function () { + socket.send('SEND\ndestination:/topic/activity\ncontent-length:20\n\n{"page":"/overview"}\u0000'); - // Subscribe for system and user notifications - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/system-notification\n\n\u0000"); - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/user/" + user.id + "/notifications\n\n\u0000"); - }); - }, 1 * 1000); + courses.forEach(function (course) { + if (user.groups.includes(course.studentGroupName)) { + subscribeCourse(course.id, 'STUDENT'); + } + if (user.groups.includes(course.teachingAssistantGroupName)) { + subscribeCourse(course.id, 'TA'); + } + if (user.groups.includes(course.instructorGroupName)) { + subscribeCourse(course.id, 'INSTRUCTOR'); + } - socket.setTimeout(function() { - socket.close(); - }, websocketConnectionTime * 1000); - }); - } - }); + // Subscribe for system and user notifications + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/system-notification\n\n\u0000'); + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/user/' + user.id + '/notifications\n\n\u0000'); + }); + }, 1 * 1000); + socket.setTimeout(function () { + socket.close(); + }, websocketConnectionTime * 1000); + }); + } + }); } diff --git a/src/test/k6/ArtemisLoginOnlyWebsocket.js b/src/test/k6/ArtemisLoginOnlyWebsocket.js index c41ee27c93c3..72f5b4247795 100644 --- a/src/test/k6/ArtemisLoginOnlyWebsocket.js +++ b/src/test/k6/ArtemisLoginOnlyWebsocket.js @@ -9,153 +9,158 @@ import ws from 'k6/ws'; export let options = { maxRedirects: 0, ext: { - "loadimpact": { - "distribution": { - "load_zone0": { - "loadZone": "amazon:de:frankfurt", - "percent": 100 - } - } - } + loadimpact: { + distribution: { + load_zone0: { + loadZone: 'amazon:de:frankfurt', + percent: 100, + }, + }, + }, }, stages: [ { - "duration": "5s", - "target": 30 + duration: '5s', + target: 30, }, { - "duration": "5s", - "target": 50 + duration: '5s', + target: 50, }, { - "duration": "5s", - "target": 80 + duration: '5s', + target: 80, }, { - "duration": "300s", - "target": 100 - } + duration: '300s', + target: 100, + }, ], - vus: 100 + vus: 100, }; -export default function() { - let defaultXSRFToken = "42d141b5-9e1c-4390-ae06-5143753b4459"; - let protocol = "https"; // https or http - let websocketProtocol = "wss"; // wss if https is used; ws if http is used - let host = "artemis.ase.in.tum.de"; // host including port if differing from 80 (http) or 443 (https) - let baseUrl = protocol + "://" + host; - - let maxTestUser = 100; // the userId will be an integer between 1 and this number - - let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password - let websocketConnectionTime = 300; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished - - let userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"; - let acceptLanguage = "en-CA,en-US;q=0.7,en;q=0.3"; - let acceptEncoding = "gzip, deflate, br"; - - let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser - let password = "__ENV.BASE_PASSWORD"; // USERID gets replaced with a random number between 1 and maxTestUser - - group("Artemis Login", function() { - let req, res; - - - // The user is randomly selected - let userId = Math.floor((Math.random() * maxTestUser)) + 1; - let currentUsername = username.replace("USERID", userId); - let currentPassword = password.replace("USERID", userId); - - // The user logs in; the authToken gets saved as we need it later - req = [{ - "method": "post", - "url": baseUrl + "/api/authenticate", - "body": "{\"username\":\"" + currentUsername + "\",\"password\":\"" + currentPassword +"\",\"rememberMe\":true}", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "X-XSRF-TOKEN": defaultXSRFToken, - "Content-Type": "application/json", - "Content-Length": "74", - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/authenticate"} - } - }]; - res = http.batch(req); - let authToken = JSON.parse(res[0].body).id_token; - - // The user requests it own information of the account - req = [{ - "method": "get", - "url": baseUrl + "/api/account", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/account"} - } - }]; - - res = http.batch(req); - - // A new XSRF Token is needed now, we have to extract it from the cookies - let xsrftoken = res[0].headers["Set-Cookie"].match('XSRF-TOKEN=(.*); path=\/(; secure)?')[1]; - - // Initiate websocket connection if connection time is set to value greater than 0 - if (websocketConnectionTime > 0) { - let websocketEndpoint = websocketProtocol + "://" + host + "/websocket/tracker/websocket"; - let websocketUrl = websocketEndpoint + "?access_token=" + authToken; - - var response = ws.connect(websocketUrl, {"tags": {"name": websocketEndpoint}}, function(socket) { - socket.on('open', function open() { - socket.send("CONNECT\nX-XSRF-TOKEN:" + xsrftoken + "\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000"); - }); - - function getSubscriptionId() { - return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 12); - } - - function subscribeCourse(courseId, role) { - socket.send("SUBSCRIBE\nid:sub-" + getSubscriptionId() + "\ndestination:/topic/course/" + courseId + "/" + role +"\n\n\u0000"); - } +export default function () { + let defaultXSRFToken = '42d141b5-9e1c-4390-ae06-5143753b4459'; + let protocol = 'https'; // https or http + let websocketProtocol = 'wss'; // wss if https is used; ws if http is used + let host = 'artemis.ase.in.tum.de'; // host including port if differing from 80 (http) or 443 (https) + let baseUrl = protocol + '://' + host; + + let maxTestUser = 100; // the userId will be an integer between 1 and this number + + let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password + let websocketConnectionTime = 300; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished + + let userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0'; + let acceptLanguage = 'en-CA,en-US;q=0.7,en;q=0.3'; + let acceptEncoding = 'gzip, deflate, br'; + + let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser + let password = '__ENV.BASE_PASSWORD'; // USERID gets replaced with a random number between 1 and maxTestUser + + group('Artemis Login', function () { + let req, res; + + // The user is randomly selected + let userId = Math.floor(Math.random() * maxTestUser) + 1; + let currentUsername = username.replace('USERID', userId); + let currentPassword = password.replace('USERID', userId); + + // The user logs in; the authToken gets saved as we need it later + req = [ + { + method: 'post', + url: baseUrl + '/api/authenticate', + body: '{"username":"' + currentUsername + '","password":"' + currentPassword + '","rememberMe":true}', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + 'X-XSRF-TOKEN': defaultXSRFToken, + 'Content-Type': 'application/json', + 'Content-Length': '74', + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/authenticate' }, + }, + }, + ]; + res = http.batch(req); + let authToken = JSON.parse(res[0].body).id_token; + + // The user requests it own information of the account + req = [ + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, + }, + }, + ]; + + res = http.batch(req); + + // A new XSRF Token is needed now, we have to extract it from the cookies + let xsrftoken = res[0].headers['Set-Cookie'].match('XSRF-TOKEN=(.*); path=/(; secure)?')[1]; + + // Initiate websocket connection if connection time is set to value greater than 0 + if (websocketConnectionTime > 0) { + let websocketEndpoint = websocketProtocol + '://' + host + '/websocket/tracker/websocket'; + let websocketUrl = websocketEndpoint + '?access_token=' + authToken; + + var response = ws.connect(websocketUrl, { tags: { name: websocketEndpoint } }, function (socket) { + socket.on('open', function open() { + socket.send('CONNECT\nX-XSRF-TOKEN:' + xsrftoken + '\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000'); + }); + + function getSubscriptionId() { + return Math.random() + .toString(36) + .replace(/[^a-z]+/g, '') + .substr(0, 12); + } - socket.setInterval(function timeout() { - socket.ping(); - // console.log("Pinging every 10sec (setInterval test)"); - }, 10000); + function subscribeCourse(courseId, role) { + socket.send('SUBSCRIBE\nid:sub-' + getSubscriptionId() + '\ndestination:/topic/course/' + courseId + '/' + role + '\n\n\u0000'); + } - // Send destination and subscription after 1 second - socket.setTimeout(function() { - socket.send("SEND\ndestination:/topic/activity\ncontent-length:20\n\n{\"page\":\"/overview\"}\u0000"); - }, 1 * 1000); + socket.setInterval(function timeout() { + socket.ping(); + // console.log("Pinging every 10sec (setInterval test)"); + }, 10000); - socket.setTimeout(function() { - socket.close(); - }, websocketConnectionTime * 1000); - }); - } - }); + // Send destination and subscription after 1 second + socket.setTimeout(function () { + socket.send('SEND\ndestination:/topic/activity\ncontent-length:20\n\n{"page":"/overview"}\u0000'); + }, 1 * 1000); + socket.setTimeout(function () { + socket.close(); + }, websocketConnectionTime * 1000); + }); + } + }); } diff --git a/src/test/k6/ArtemisOnlyDashboard.js b/src/test/k6/ArtemisOnlyDashboard.js index 27b4e2ebbeae..c770dd198421 100644 --- a/src/test/k6/ArtemisOnlyDashboard.js +++ b/src/test/k6/ArtemisOnlyDashboard.js @@ -1,28 +1,28 @@ import { group, sleep } from 'k6'; import http from 'k6/http'; import ws from 'k6/ws'; -import { Trend } from "k6/metrics"; +import { Trend } from 'k6/metrics'; // Version: 1.1 // Creator: Firefox // Browser: Firefox -var rest_call_metrics = new Trend("rest_call_metrics"); +var rest_call_metrics = new Trend('rest_call_metrics'); export let options = { maxRedirects: 0, ext: { - "loadimpact": { - "distribution": { - "load_zone0": { - "loadZone": "amazon:de:frankfurt", - "percent": 100 - } - } - } + loadimpact: { + distribution: { + load_zone0: { + loadZone: 'amazon:de:frankfurt', + percent: 100, + }, + }, + }, }, stages: [ - /*{ + /*{ "duration": "15s", "target": 10 }, @@ -58,133 +58,138 @@ export let options = { "duration": "15s", "target": 90 },*/ - { - "duration": "300s", - "target": 100 - } + { + duration: '300s', + target: 100, + }, ], - vus: 70 + vus: 70, }; -export default function() { - let defaultXSRFToken = "42d141b5-9e1c-4390-ae06-5143753b4459"; - let protocol = "http"; // https or http - let websocketProtocol = "ws"; // wss if https is used; ws if http is used - let host = "nginx:80"; // host including port if differing from 80 (http) or 443 (https) - let baseUrl = protocol + "://" + host; - - let maxTestUser = 100; // the userId will be an integer between 1 and this number - - let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password - let websocketConnectionTime = 100; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished - - let userAgent = "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0"; - let acceptLanguage = "en-CA,en-US;q=0.7,en;q=0.3"; - let acceptEncoding = "gzip, deflate, br"; - - let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser - let password = "__ENV.BASE_PASSWORD"; // USERID gets replaced with a random number between 1 and maxTestUser - - group("Artemis Login", function() { - let req, res; - - // The user is randomly selected - let userId = Math.floor((Math.random() * maxTestUser)) + 1; - let currentUsername = username.replace("USERID", userId); - let currentPassword = password.replace("USERID", userId); - - // The user logs in; the authToken gets saved as we need it later - req = [{ - "method": "post", - "url": baseUrl + "/api/authenticate", - "body": "{\"username\":\"" + currentUsername + "\",\"password\":\"" + currentPassword +"\",\"rememberMe\":true}", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "X-XSRF-TOKEN": defaultXSRFToken, - "Content-Type": "application/json", - "Content-Length": "74", - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/authenticate"} - } - }]; - res = http.batch(req); - let authToken = JSON.parse(res[0].body).id_token; - - // The user requests it own information of the account - req = [{ - "method": "get", - "url": baseUrl + "/api/account", - "params": { - "cookies": { - "XSRF-TOKEN": defaultXSRFToken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/account"} - } - }]; - - res = http.batch(req); - - // A new XSRF Token is needed now, we have to extract it from the cookies - let xsrftoken = res[0].headers["Set-Cookie"].match('XSRF-TOKEN=(.*); path=\/(; secure)?')[1]; - - // Extract user as we need it for some websocket information - let user = JSON.parse(res[0].body); - - // Some more calls (dashboard, notification, courses to register) are made - var i; - for (i = 0; i < 5; i++) { - req = [{ - "method": "get", - "url": baseUrl + "/api/courses/for-dashboard", - "params": { - "cookies": { - "XSRF-TOKEN": xsrftoken - }, - "headers": { - "Host": host, - "User-Agent": userAgent, - "Accept": "application/json, text/plain, */*", - "Accept-Language": acceptLanguage, - "Accept-Encoding": acceptEncoding, - "Referer": baseUrl + "/", - "Authorization": "Bearer " + authToken, - "Connection": "keep-alive", - "TE": "Trailers" - }, - "tags": {"name": baseUrl + "/api/courses/for-dashboard"} - } - }]; - res = http.batch(req); - rest_call_metrics.add(res[0].timings.waiting); - } - sleep(Math.random() * 30); - // sleep(5000); - }); - +export default function () { + let defaultXSRFToken = '42d141b5-9e1c-4390-ae06-5143753b4459'; + let protocol = 'http'; // https or http + let websocketProtocol = 'ws'; // wss if https is used; ws if http is used + let host = 'nginx:80'; // host including port if differing from 80 (http) or 443 (https) + let baseUrl = protocol + '://' + host; + + let maxTestUser = 100; // the userId will be an integer between 1 and this number + + let delayBeforeLogin = 1; // Time in seconds the simulated user needs to enter username/password + let websocketConnectionTime = 100; // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished + + let userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0'; + let acceptLanguage = 'en-CA,en-US;q=0.7,en;q=0.3'; + let acceptEncoding = 'gzip, deflate, br'; + + let username = __ENV.BASE_USERNAME; // USERID gets replaced with a random number between 1 and maxTestUser + let password = '__ENV.BASE_PASSWORD'; // USERID gets replaced with a random number between 1 and maxTestUser + + group('Artemis Login', function () { + let req, res; + + // The user is randomly selected + let userId = Math.floor(Math.random() * maxTestUser) + 1; + let currentUsername = username.replace('USERID', userId); + let currentPassword = password.replace('USERID', userId); + + // The user logs in; the authToken gets saved as we need it later + req = [ + { + method: 'post', + url: baseUrl + '/api/authenticate', + body: '{"username":"' + currentUsername + '","password":"' + currentPassword + '","rememberMe":true}', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + 'X-XSRF-TOKEN': defaultXSRFToken, + 'Content-Type': 'application/json', + 'Content-Length': '74', + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/authenticate' }, + }, + }, + ]; + res = http.batch(req); + let authToken = JSON.parse(res[0].body).id_token; + + // The user requests it own information of the account + req = [ + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, + }, + }, + ]; + + res = http.batch(req); + + // A new XSRF Token is needed now, we have to extract it from the cookies + let xsrftoken = res[0].headers['Set-Cookie'].match('XSRF-TOKEN=(.*); path=/(; secure)?')[1]; + + // Extract user as we need it for some websocket information + let user = JSON.parse(res[0].body); + + // Some more calls (dashboard, notification, courses to register) are made + var i; + for (i = 0; i < 5; i++) { + req = [ + { + method: 'get', + url: baseUrl + '/api/courses/for-dashboard', + params: { + cookies: { + 'XSRF-TOKEN': xsrftoken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/courses/for-dashboard' }, + }, + }, + ]; + res = http.batch(req); + rest_call_metrics.add(res[0].timings.waiting); + } + sleep(Math.random() * 30); + // sleep(5000); + }); } export function teardown() { - console.log(rest_call_metrics.avg); + console.log(rest_call_metrics.avg); } diff --git a/src/test/k6/CodeEditor.js b/src/test/k6/CodeEditor.js index fcb15ecac6fa..236474d15f57 100644 --- a/src/test/k6/CodeEditor.js +++ b/src/test/k6/CodeEditor.js @@ -1,14 +1,7 @@ import { login } from './requests/requests.js'; import { group, sleep } from 'k6'; import { deleteCourse, newCourse } from './requests/course.js'; -import { - startExercise, - createExercise, - deleteExercise, - ParticipationSimulation, - simulateSubmission, - TestResult -} from './requests/programmingExercise.js'; +import { startExercise, createExercise, deleteExercise, ParticipationSimulation, simulateSubmission, TestResult } from './requests/programmingExercise.js'; import { buildErrorContent } from './resource/constants.js'; // Version: 1.1 @@ -19,7 +12,7 @@ export let options = { maxRedirects: 0, iterations: __ENV.ITERATIONS, vus: __ENV.ITERATIONS, - rps: 5 + rps: 5, }; const adminUsername = __ENV.ADMIN_USERNAME; @@ -44,14 +37,14 @@ export function setup() { return { exerciseId: exerciseId, courseId: courseId }; } -export default function(data) { +export default function (data) { const websocketConnectionTime = parseFloat(__ENV.TIMEOUT_PARTICIPATION); // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished // Delay so that not all users start at the same time, batches of 3 users per second const delay = Math.floor(__VU / 3); sleep(delay); - group('Artemis Programming Exercise Participation Loadtest', function() { + group('Artemis Programming Exercise Participation Loadtest', function () { // The user is randomly selected const userId = __VU; // Math.floor((Math.random() * maxTestUser)) + 1; const currentUsername = baseUsername.replace('USERID', userId); @@ -71,7 +64,7 @@ export default function(data) { } }); - return data; + return data; } export function teardown(data) { diff --git a/src/test/k6/ProgrammingExerciseAPIs.js b/src/test/k6/ProgrammingExerciseAPIs.js index d4efd910e1cc..d9f13eb0720a 100644 --- a/src/test/k6/ProgrammingExerciseAPIs.js +++ b/src/test/k6/ProgrammingExerciseAPIs.js @@ -1,11 +1,11 @@ import { group, sleep } from 'k6'; -import { login } from "./requests/requests.js"; -import { createProgrammingExercise, startExercise, simulateSubmission, ParticipationSimulation, TestResult, deleteProgrammingExercise } from "./requests/programmingExercise.js"; -import { deleteCourse, newCourse, addUserToStudentsInCourse, addUserToInstructorsInCourse } from "./requests/course.js"; +import { login } from './requests/requests.js'; +import { createProgrammingExercise, startExercise, simulateSubmission, ParticipationSimulation, TestResult, deleteProgrammingExercise } from './requests/programmingExercise.js'; +import { deleteCourse, newCourse, addUserToStudentsInCourse, addUserToInstructorsInCourse } from './requests/course.js'; import { newUser, getUser, updateUser, createUsersIfNeeded } from './requests/user.js'; -import {allSuccessfulContentJava, buildErrorContentJava, someSuccessfulErrorContentJava} from "./resource/constants_java.js"; -import {allSuccessfulContentPython, buildErrorContentPython, someSuccessfulErrorContentPython} from "./resource/constants_python.js"; -import {allSuccessfulContentC, buildErrorContentC, someSuccessfulErrorContentC} from "./resource/constants_c.js"; +import { allSuccessfulContentJava, buildErrorContentJava, someSuccessfulErrorContentJava } from './resource/constants_java.js'; +import { allSuccessfulContentPython, buildErrorContentPython, someSuccessfulErrorContentPython } from './resource/constants_python.js'; +import { allSuccessfulContentC, buildErrorContentC, someSuccessfulErrorContentC } from './resource/constants_c.js'; export const options = { maxRedirects: 0, @@ -13,21 +13,20 @@ export const options = { vus: __ENV.ITERATIONS, rps: 4, setupTimeout: '240s', - teardownTimeout: '240s' + teardownTimeout: '240s', }; const adminUsername = __ENV.ADMIN_USERNAME; const adminPassword = __ENV.ADMIN_PASSWORD; let baseUsername = __ENV.BASE_USERNAME; let basePassword = __ENV.BASE_PASSWORD; -let programmingLanguage= __ENV.PROGRAMMING_LANGUAGE; +let programmingLanguage = __ENV.PROGRAMMING_LANGUAGE; export function setup() { - - console.log("__ENV.CREATE_USERS: " + __ENV.CREATE_USERS); - console.log("__ENV.TIMEOUT_PARTICIPATION: " + __ENV.TIMEOUT_PARTICIPATION); - console.log("__ENV.TIMEOUT_EXERCISE: " + __ENV.TIMEOUT_EXERCISE); - console.log("__ENV.ITERATIONS: " + __ENV.ITERATIONS); + console.log('__ENV.CREATE_USERS: ' + __ENV.CREATE_USERS); + console.log('__ENV.TIMEOUT_PARTICIPATION: ' + __ENV.TIMEOUT_PARTICIPATION); + console.log('__ENV.TIMEOUT_EXERCISE: ' + __ENV.TIMEOUT_EXERCISE); + console.log('__ENV.ITERATIONS: ' + __ENV.ITERATIONS); let artemis, exerciseId, course, userId; @@ -47,7 +46,7 @@ export function setup() { // it might be necessary that the newly created groups or accounts are synced with the version control and continuous integration servers, so we wait for 1 minute const timeoutExercise = parseFloat(__ENV.TIMEOUT_EXERCISE); if (timeoutExercise > 0) { - console.log("Wait " + timeoutExercise + "s before creating the programming exercise so that the setup can finish properly"); + console.log('Wait ' + timeoutExercise + 's before creating the programming exercise so that the setup can finish properly'); sleep(timeoutExercise); } @@ -76,7 +75,7 @@ export default function (data) { sleep(delay * 3); let someSuccessfulErrorContent, allSuccessfulContent, buildErrorContent, somePassedString; - switch(programmingLanguage) { + switch (programmingLanguage) { case 'JAVA': someSuccessfulErrorContent = someSuccessfulErrorContentJava; allSuccessfulContent = allSuccessfulContentJava; @@ -97,7 +96,7 @@ export default function (data) { break; } - group('Participate in Programming Exercise', function() { + group('Participate in Programming Exercise', function () { let participationId = startExercise(artemis, courseId, exerciseId); if (participationId) { // partial success, then 100%, then build error -- wait some time between submissions in order to the build server time for the result @@ -106,8 +105,9 @@ export default function (data) { simulation = new ParticipationSimulation(timeoutParticipation, exerciseId, participationId, allSuccessfulContent); simulateSubmission(artemis, simulation, TestResult.SUCCESS); simulation = new ParticipationSimulation(timeoutParticipation, exerciseId, participationId, buildErrorContent); - if (programmingLanguage === 'C') { // C builds do never fail - they will only show 0/20 passed - simulateSubmission(artemis, simulation, TestResult.FAIL, "0 of 20 passed"); + if (programmingLanguage === 'C') { + // C builds do never fail - they will only show 0/20 passed + simulateSubmission(artemis, simulation, TestResult.FAIL, '0 of 20 passed'); } else { simulateSubmission(artemis, simulation, TestResult.BUILD_ERROR); } @@ -121,7 +121,6 @@ export default function (data) { } export function teardown(data) { - const shouldCleanup = __ENV.CLEANUP === true || __ENV.CLEANUP === 'true'; if (shouldCleanup) { const artemis = login(adminUsername, adminPassword); diff --git a/src/test/k6/QuizExerciseAPIs.js b/src/test/k6/QuizExerciseAPIs.js index 4269a14c5de8..0720387b32c4 100644 --- a/src/test/k6/QuizExerciseAPIs.js +++ b/src/test/k6/QuizExerciseAPIs.js @@ -1,9 +1,9 @@ import { login } from './requests/requests.js'; import { group, sleep } from 'k6'; -import { getQuizQuestions, simulateQuizWork } from "./requests/quiz.js"; -import {newCourse, deleteCourse} from "./requests/course.js"; -import {createUsersIfNeeded} from "./requests/user.js"; -import {createQuizExercise, deleteQuizExercise} from "./requests/quiz.js"; +import { getQuizQuestions, simulateQuizWork } from './requests/quiz.js'; +import { newCourse, deleteCourse } from './requests/course.js'; +import { createUsersIfNeeded } from './requests/user.js'; +import { createQuizExercise, deleteQuizExercise } from './requests/quiz.js'; // Version: 1.1 // Creator: Firefox @@ -15,7 +15,7 @@ export let options = { vus: __ENV.ITERATIONS, rps: 5, setupTimeout: '240s', - teardownTimeout: '240s' + teardownTimeout: '240s', }; const adminUsername = __ENV.ADMIN_USERNAME; @@ -24,11 +24,10 @@ let baseUsername = __ENV.BASE_USERNAME; let basePassword = __ENV.BASE_PASSWORD; export function setup() { - - console.log("__ENV.CREATE_USERS: " + __ENV.CREATE_USERS); - console.log("__ENV.TIMEOUT_PARTICIPATION: " + __ENV.TIMEOUT_PARTICIPATION); - console.log("__ENV.TIMEOUT_EXERCISE: " + __ENV.TIMEOUT_EXERCISE); - console.log("__ENV.ITERATIONS: " + __ENV.ITERATIONS); + console.log('__ENV.CREATE_USERS: ' + __ENV.CREATE_USERS); + console.log('__ENV.TIMEOUT_PARTICIPATION: ' + __ENV.TIMEOUT_PARTICIPATION); + console.log('__ENV.TIMEOUT_EXERCISE: ' + __ENV.TIMEOUT_EXERCISE); + console.log('__ENV.ITERATIONS: ' + __ENV.ITERATIONS); let artemis, exerciseId, course, userId; @@ -48,7 +47,7 @@ export function setup() { // it might be necessary that the newly created groups or accounts are synced with the version control and continuous integration servers, so we wait for 1 minute const timeoutExercise = parseFloat(__ENV.TIMEOUT_EXERCISE); if (timeoutExercise > 0) { - console.log("Wait " + timeoutExercise + "s before creating the programming exercise so that the setup can finish properly"); + console.log('Wait ' + timeoutExercise + 's before creating the programming exercise so that the setup can finish properly'); sleep(timeoutExercise); } @@ -60,14 +59,14 @@ export function setup() { return { exerciseId: exerciseId, courseId: course.id }; } -export default function(data) { +export default function (data) { const websocketConnectionTime = parseFloat(__ENV.TIMEOUT_PARTICIPATION); // Time in seconds the websocket is kept open, if set to 0 no websocket connection is estahblished // Delay so that not all users start at the same time, batches of 50 users per second const delay = Math.floor(__VU / 50); sleep(delay); - group('Artemis Programming Exercise Participation Websocket Stresstest', function() { + group('Artemis Programming Exercise Participation Websocket Stresstest', function () { const userId = __VU; const currentUsername = baseUsername.replace('USERID', userId); const currentPassword = basePassword.replace('USERID', userId); @@ -85,7 +84,6 @@ export default function(data) { } export function teardown(data) { - const shouldCleanup = __ENV.CLEANUP === true || __ENV.CLEANUP === 'true'; if (shouldCleanup) { const artemis = login(adminUsername, adminPassword); diff --git a/src/test/k6/requests/course.js b/src/test/k6/requests/course.js index 8e2c3bfa3eac..0f6fa1687d53 100644 --- a/src/test/k6/requests/course.js +++ b/src/test/k6/requests/course.js @@ -20,7 +20,7 @@ export function newCourse(artemis) { const res = artemis.post(COURSES, course); if (res[0].status !== 201) { - console.log("ERROR when creating a new course. Response headers:"); + console.log('ERROR when creating a new course. Response headers:'); for (let [key, value] of Object.entries(res[0].headers)) { console.log(`${key}: ${value}`); } @@ -33,22 +33,22 @@ export function newCourse(artemis) { export function addUserToStudentsInCourse(artemis, username, courseId) { const res = artemis.post(COURSE_STUDENTS(courseId, username)); - console.log("Add user " + username + " to students in course " + courseId + " status: " + res[0].status); + console.log('Add user ' + username + ' to students in course ' + courseId + ' status: ' + res[0].status); } export function removeUserFromStudentsInCourse(artemis, username, courseId) { const res = artemis.delete(COURSE_STUDENTS(courseId, username)); - console.log("Remove user " + username + " from students in course " + courseId + " status: " + res[0].status); + console.log('Remove user ' + username + ' from students in course ' + courseId + ' status: ' + res[0].status); } export function addUserToInstructorsInCourse(artemis, username, courseId) { const res = artemis.post(COURSE_INSTRUCTORS(courseId, username)); - console.log("Add user " + username + " to instructors in course " + courseId + " status: " + res[0].status); + console.log('Add user ' + username + ' to instructors in course ' + courseId + ' status: ' + res[0].status); } export function removeUserFromInstructorsInCourse(artemis, username, courseId) { const res = artemis.delete(COURSE_INSTRUCTORS(courseId, username)); - console.log("Remove user " + username + " from instructors in course " + courseId + " status: " + res[0].status); + console.log('Remove user ' + username + ' from instructors in course ' + courseId + ' status: ' + res[0].status); } export function deleteCourse(artemis, courseId) { diff --git a/src/test/k6/requests/endpoints.js b/src/test/k6/requests/endpoints.js index 6718853e6717..bbce6ab003c2 100644 --- a/src/test/k6/requests/endpoints.js +++ b/src/test/k6/requests/endpoints.js @@ -1,10 +1,10 @@ -export const PROGRAMMING_EXERCISES_SETUP = "/programming-exercises/setup"; -export const PROGRAMMING_EXERCISES = "/programming-exercises"; +export const PROGRAMMING_EXERCISES_SETUP = '/programming-exercises/setup'; +export const PROGRAMMING_EXERCISES = '/programming-exercises'; export const PROGRAMMING_EXERCISE = (exerciseId) => `${PROGRAMMING_EXERCISES}/${exerciseId}`; -export const QUIZ_EXERCISES = "/quiz-exercises"; +export const QUIZ_EXERCISES = '/quiz-exercises'; export const QUIZ_EXERCISE = (exerciseId) => `${QUIZ_EXERCISES}/${exerciseId}`; -export const COURSES = "/courses"; -export const USERS = "/users"; +export const COURSES = '/courses'; +export const USERS = '/users'; export const COURSE = (courseId) => `${COURSES}/${courseId}`; export const COURSE_STUDENTS = (courseId, username) => `${COURSES}/${courseId}/students/${username}`; export const COURSE_TUTORS = (courseId, username) => `${COURSES}/${courseId}/tutors/${username}`; diff --git a/src/test/k6/requests/programmingExercise.js b/src/test/k6/requests/programmingExercise.js index 684e19b0dd29..5ea3f6cfb4d8 100644 --- a/src/test/k6/requests/programmingExercise.js +++ b/src/test/k6/requests/programmingExercise.js @@ -1,16 +1,9 @@ -import {nextAlphanumeric, nextWSSubscriptionId} from '../util/utils.js'; -import { - COMMIT, - NEW_FILE, - PARTICIPATION_WITH_RESULT, - PARTICIPATIONS, - PROGRAMMING_EXERCISE, - PROGRAMMING_EXERCISES_SETUP -} from './endpoints.js'; -import {fail, sleep} from 'k6'; -import {programmingExerciseProblemStatementJava} from "../resource/constants_java.js"; -import {programmingExerciseProblemStatementPython} from "../resource/constants_python.js"; -import {programmingExerciseProblemStatementC} from "../resource/constants_c.js"; +import { nextAlphanumeric, nextWSSubscriptionId } from '../util/utils.js'; +import { COMMIT, NEW_FILE, PARTICIPATION_WITH_RESULT, PARTICIPATIONS, PROGRAMMING_EXERCISE, PROGRAMMING_EXERCISES_SETUP } from './endpoints.js'; +import { fail, sleep } from 'k6'; +import { programmingExerciseProblemStatementJava } from '../resource/constants_java.js'; +import { programmingExerciseProblemStatementPython } from '../resource/constants_python.js'; +import { programmingExerciseProblemStatementC } from '../resource/constants_c.js'; export function ParticipationSimulation(timeout, exerciseId, participationId, content) { this.timeout = timeout; @@ -19,30 +12,32 @@ export function ParticipationSimulation(timeout, exerciseId, participationId, co this.newFiles = content.newFiles; this.content = content.content; - this.returnsExpectedResult = function(result, expectedResult, resultString) { - console.log("Received test result " + result.successful + ", " + result.resultString); + this.returnsExpectedResult = function (result, expectedResult, resultString) { + console.log('Received test result ' + result.successful + ', ' + result.resultString); switch (expectedResult) { - case TestResult.SUCCESS: { - if(!result.successful) fail(`ERROR: The result for participation ${participationId} was not successful!`); - } - break; - case TestResult.FAIL: { - if(result.successful || !result.hasFeedback || result.resultString !== resultString) - fail(`ERROR: The result for participation ${participationId} did not fail with ${resultString}! Was ${result.resultString}`) - } - break; + case TestResult.SUCCESS: + { + if (!result.successful) fail(`ERROR: The result for participation ${participationId} was not successful!`); + } + break; + case TestResult.FAIL: + { + if (result.successful || !result.hasFeedback || result.resultString !== resultString) + fail(`ERROR: The result for participation ${participationId} did not fail with ${resultString}! Was ${result.resultString}`); + } + break; default: { - if(result.successful || result.hasFeedback) fail(`ERROR: The result for participation ${participationId} contained no build errors!`) + if (result.successful || result.hasFeedback) fail(`ERROR: The result for participation ${participationId} contained no build errors!`); } } }; - this.extractResultFromWebSocketMessage = function(message) { + this.extractResultFromWebSocketMessage = function (message) { const resReg = /(.*\n\n)([^\u0000]*)(\u0000)/g; const match = resReg.exec(message); return JSON.parse(match[2]); - } + }; } export function getLatestResult(artemis, participationId) { @@ -60,7 +55,7 @@ export function getLatestResult(artemis, participationId) { export const TestResult = { SUCCESS: 'success', FAIL: 'failure', - BUILD_ERROR: 'error' + BUILD_ERROR: 'error', }; export function createProgrammingExercise(artemis, courseId, programmingLanguage) { @@ -82,7 +77,7 @@ export function createProgrammingExercise(artemis, courseId, programmingLanguage // The actual exercise const exercise = { title: 'TEST ' + nextAlphanumeric(10), - shortName: 'TEST'+ nextAlphanumeric(5).toUpperCase(), + shortName: 'TEST' + nextAlphanumeric(5).toUpperCase(), maxScore: 42, assessmentType: 'AUTOMATIC', type: 'programming', @@ -94,13 +89,13 @@ export function createProgrammingExercise(artemis, courseId, programmingLanguage sequentialTestRuns: false, mode: 'INDIVIDUAL', course: { - id: courseId - } + id: courseId, + }, }; res = artemis.post(PROGRAMMING_EXERCISES_SETUP, exercise); if (res[0].status !== 201) { - console.log("ERROR when creating a new programming exercise. Response headers:"); + console.log('ERROR when creating a new programming exercise. Response headers:'); for (let [key, value] of Object.entries(res[0].headers)) { console.log(`${key}: ${value}`); } @@ -115,7 +110,7 @@ export function createProgrammingExercise(artemis, courseId, programmingLanguage export function deleteProgrammingExercise(artemis, exerciseId) { const res = artemis.delete(PROGRAMMING_EXERCISE(exerciseId), { deleteStudentReposBuildPlans: true, - deleteBaseReposBuildPlans: true + deleteBaseReposBuildPlans: true, }); if (res[0].status !== 200) { fail('Could not delete exercise (' + res[0].status + ')! Response was + ' + res[0].body); @@ -152,20 +147,27 @@ export function createNewFile(artemis, participationId, filename) { export function simulateSubmission(artemis, participationSimulation, expectedResult, resultString) { // First, we have to create all new files - participationSimulation.newFiles.forEach(file => createNewFile(artemis, participationSimulation.participationId, file)); + participationSimulation.newFiles.forEach((file) => createNewFile(artemis, participationSimulation.participationId, file)); artemis.websocket(function (socket) { // Send changes via websocket function submitChange(content) { const contentString = JSON.stringify(content); - const changeMessage = 'SEND\ndestination:/topic/repository/' + participationSimulation.participationId + '/files\ncontent-length:' + contentString.length + '\n\n' + contentString + '\u0000'; + const changeMessage = + 'SEND\ndestination:/topic/repository/' + + participationSimulation.participationId + + '/files\ncontent-length:' + + contentString.length + + '\n\n' + + contentString + + '\u0000'; socket.send(changeMessage); socket.send('SUBSCRIBE\nid:sub-' + nextWSSubscriptionId() + '\ndestination:/user/topic/repository/' + participationSimulation.participationId + '/files\n\n\u0000'); } // Subscribe to new results and participations function subscribe(exerciseId, participationId) { - socket.send('SUBSCRIBE\nid:sub-' + nextWSSubscriptionId() + '\ndestination:/topic/participation/' + participationId +'/newResults\n\n\u0000'); + socket.send('SUBSCRIBE\nid:sub-' + nextWSSubscriptionId() + '\ndestination:/topic/participation/' + participationId + '/newResults\n\n\u0000'); socket.send('SUBSCRIBE\nid:sub-' + nextWSSubscriptionId() + '\ndestination:/user/topic/exercise/' + exerciseId + '/participation\n\n\u0000'); } @@ -174,17 +176,17 @@ export function simulateSubmission(artemis, participationSimulation, expectedRes socket.ping(); }, 10000); - socket.setTimeout(function() { + socket.setTimeout(function () { subscribe(participationSimulation.exerciseId, participationSimulation.participationId); }, 5 * 1000); - socket.setTimeout(function() { + socket.setTimeout(function () { submitChange(participationSimulation.content); - console.log('SEND file data for test user ' + __VU) + console.log('SEND file data for test user ' + __VU); }, 10 * 1000); // Commit changes - socket.setTimeout(function() { + socket.setTimeout(function () { artemis.post(COMMIT(participationSimulation.participationId)); console.log('COMMIT changes for test user ' + __VU); }, 15 * 1000); @@ -200,7 +202,7 @@ export function simulateSubmission(artemis, participationSimulation, expectedRes }); // Fail after timeout - socket.setTimeout(function() { + socket.setTimeout(function () { socket.close(); // Try to GET latest result console.log('Websocket timed out, trying to GET now'); @@ -210,7 +212,6 @@ export function simulateSubmission(artemis, participationSimulation, expectedRes } else { fail('ERROR: Did not receive result for test user ' + __VU); } - }, participationSimulation.timeout * 1000); }); } diff --git a/src/test/k6/requests/quiz.js b/src/test/k6/requests/quiz.js index 64b5efdcc634..98a99632d100 100644 --- a/src/test/k6/requests/quiz.js +++ b/src/test/k6/requests/quiz.js @@ -1,7 +1,7 @@ -import {PARTICIPATION, QUIZ_EXERCISES} from "./endpoints.js"; -import {fail, sleep} from 'k6'; -import {nextAlphanumeric, nextWSSubscriptionId, randomArrayValue} from "../util/utils.js"; -import {QUIZ_EXERCISE} from "./endpoints.js"; +import { PARTICIPATION, QUIZ_EXERCISES } from './endpoints.js'; +import { fail, sleep } from 'k6'; +import { nextAlphanumeric, nextWSSubscriptionId, randomArrayValue } from '../util/utils.js'; +import { QUIZ_EXERCISE } from './endpoints.js'; export function createQuizExercise(artemis, course) { let res; @@ -24,12 +24,12 @@ export function createQuizExercise(artemis, course) { isVisibleBeforeStart: false, mode: 'INDIVIDUAL', course: course, - quizQuestions: generateQuizQuestions(10) + quizQuestions: generateQuizQuestions(10), }; res = artemis.post(QUIZ_EXERCISES, exercise); if (res[0].status !== 201) { - console.log("ERROR when creating a new quiz exercise. Response headers:"); + console.log('ERROR when creating a new quiz exercise. Response headers:'); for (let [key, value] of Object.entries(res[0].headers)) { console.log(`${key}: ${value}`); } @@ -39,13 +39,13 @@ export function createQuizExercise(artemis, course) { console.log('CREATED new quiz exercise, ID=' + exerciseId); console.log('Setting quiz to visible'); - res = artemis.put(QUIZ_EXERCISE(exerciseId) + "/set-visible"); + res = artemis.put(QUIZ_EXERCISE(exerciseId) + '/set-visible'); if (res[0].status !== 200) { fail('Could not set quiz to visible (' + res[0].status + ')! Response was + ' + res[0].body); } console.log('Starting quiz'); - res = artemis.put(QUIZ_EXERCISE(exerciseId) + "/start-now"); + res = artemis.put(QUIZ_EXERCISE(exerciseId) + '/start-now'); if (res[0].status !== 200) { fail('Could not start quiz (' + res[0].status + ')! Response was + ' + res[0].body); } @@ -66,7 +66,7 @@ export function generateQuizQuestions(amount) { invalid: false, hint: 'Some question hint', exportQuiz: 'false', - answerOptions: generateAnswerOptions() + answerOptions: generateAnswerOptions(), }; questions.push(question); } @@ -80,14 +80,14 @@ export function generateQuizQuestions(amount) { hint: 'Correct answer hint', invalid: false, isCorrect: true, - text: 'Correct answer option' + text: 'Correct answer option', }; let wrongAnswerOption = { explanation: 'Wrong answer explanation', hint: 'Wrong answer hint', invalid: false, isCorrect: false, - text: 'Wrong answer option' + text: 'Wrong answer option', }; answerOptions.push(correctAnswerOption); @@ -117,14 +117,14 @@ export function getQuizQuestions(artemis, courseId, exerciseId) { export function simulateQuizWork(artemis, exerciseId, questions, timeout) { artemis.websocket(function (socket) { function subscribe() { - socket.send('SUBSCRIBE\nid:sub-' + nextWSSubscriptionId() + '\ndestination:/user/topic/quizExercise/' + exerciseId +'/submission\n\n\u0000'); + socket.send('SUBSCRIBE\nid:sub-' + nextWSSubscriptionId() + '\ndestination:/user/topic/quizExercise/' + exerciseId + '/submission\n\n\u0000'); } function submitRandomAnswer() { const answer = { submissionExerciseType: 'quiz', submitted: false, - submittedAnswers: questions.map(q => generateAnswer(q)) + submittedAnswers: questions.map((q) => generateAnswer(q)), }; const answerString = JSON.stringify(answer); const wsMessage = `SEND\ndestination:/topic/quizExercise/${exerciseId}/submission\ncontent-length:${answerString.length}\n\n${answerString}\u0000`; @@ -137,12 +137,12 @@ export function simulateQuizWork(artemis, exerciseId, questions, timeout) { return { type: question.type, quizQuestion: question, - selectedOptions: [randAnswer] + selectedOptions: [randAnswer], }; } // Subscribe to callback response from server (response after submitted answer - socket.setTimeout(function() { + socket.setTimeout(function () { subscribe(); }, 5 * 1000); @@ -156,13 +156,13 @@ export function simulateQuizWork(artemis, exerciseId, questions, timeout) { }); // submit new quiz answer - socket.setTimeout(function() { + socket.setTimeout(function () { submitRandomAnswer(); }, 10 * 1000); // Stop after timeout - socket.setTimeout(function() { + socket.setTimeout(function () { socket.close(); }, timeout * 1000); - }) + }); } diff --git a/src/test/k6/requests/requests.js b/src/test/k6/requests/requests.js index 46f9520d6afc..f13f337530bf 100644 --- a/src/test/k6/requests/requests.js +++ b/src/test/k6/requests/requests.js @@ -1,48 +1,52 @@ import http from 'k6/http'; import ws from 'k6/ws'; -import {fail} from 'k6'; +import { fail } from 'k6'; -const defaultXSRFToken = "42d141b5-9e1c-4390-ae06-5143753b4459"; -const protocol = "https"; // https or http -const websocketProtocol = "wss"; // wss if https is used; ws if http is used +const defaultXSRFToken = '42d141b5-9e1c-4390-ae06-5143753b4459'; +const protocol = 'https'; // https or http +const websocketProtocol = 'wss'; // wss if https is used; ws if http is used const host = __ENV.BASE_URL; // host including port if differing from 80 (http) or 443 (https) -const baseUrl = protocol + "://" + host; +const baseUrl = protocol + '://' + host; const userAgent = 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0'; const acceptLanguage = 'en-CA,en-US;q=0.7,en;q=0.3'; const acceptEncoding = 'gzip, deflate, br'; -const request = function(method, endpoint, authToken, xsrftoken, body, params) { +const request = function (method, endpoint, authToken, xsrftoken, body, params) { let paramString; if (params) { - paramString = Object.keys(params).map(key => key + '=' + params[key]).join('&'); + paramString = Object.keys(params) + .map((key) => key + '=' + params[key]) + .join('&'); } let url = baseUrl + '/api' + endpoint + (paramString ? '?' + paramString : ''); - let req = [{ - method: method, - url: url, - body: body ? JSON.stringify(body) : null, - params: { - 'cookies': { - 'XSRF-TOKEN': xsrftoken + let req = [ + { + method: method, + url: url, + body: body ? JSON.stringify(body) : null, + params: { + cookies: { + 'XSRF-TOKEN': xsrftoken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + 'X-XSRF-TOKEN': xsrftoken, + 'Content-Type': 'application/json', + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: url }, }, - 'headers': { - 'Host': host, - 'User-Agent': userAgent, - 'Accept': 'application/json, text/plain, */*', - 'Accept-Language': acceptLanguage, - 'Accept-Encoding': acceptEncoding, - 'Referer': baseUrl + '/', - 'Authorization': 'Bearer ' + authToken, - 'X-XSRF-TOKEN': xsrftoken, - 'Content-Type': 'application/json', - 'Connection': 'keep-alive', - 'TE': 'Trailers' - }, - 'tags': {name: url} - } - }]; + }, + ]; return http.batch(req); }; @@ -53,29 +57,31 @@ export function login(username, password) { console.log('Try to login with ' + username + ':' + password); // The user logs in; the authToken gets saved as we need it later - req = [{ - 'method': 'post', - 'url': baseUrl + '/api/authenticate', - 'body': '{"username":"' + username + '","password":"' + password + '","rememberMe":true}', - 'params': { - 'cookies': { - 'XSRF-TOKEN': defaultXSRFToken - }, - 'headers': { - 'Host': host, - 'User-Agent': userAgent, - 'Accept': 'application/json, text/plain, */*', - 'Accept-Language': acceptLanguage, - 'Accept-Encoding': acceptEncoding, - 'Referer': baseUrl + '/', - 'X-XSRF-TOKEN': defaultXSRFToken, - 'Content-Type': 'application/json', - 'Connection': 'keep-alive', - 'TE': 'Trailers' + req = [ + { + method: 'post', + url: baseUrl + '/api/authenticate', + body: '{"username":"' + username + '","password":"' + password + '","rememberMe":true}', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + 'X-XSRF-TOKEN': defaultXSRFToken, + 'Content-Type': 'application/json', + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/authenticate' }, }, - 'tags': {'name': baseUrl + '/api/authenticate'} - } - }]; + }, + ]; res = http.batch(req); if (res[0].status !== 200) { fail('Failed to login as user ' + username + ' (' + res[0].status + ')! Response was + ' + res[0].body); @@ -84,27 +90,29 @@ export function login(username, password) { // console.log('GOT authToken ' + authToken + ' for user ' + username); // The user requests it own information of the account - req = [{ - 'method': 'get', - 'url': baseUrl + '/api/account', - 'params': { - 'cookies': { - 'XSRF-TOKEN': defaultXSRFToken - }, - 'headers': { - 'Host': host, - 'User-Agent': userAgent, - 'Accept': 'application/json, text/plain, */*', - 'Accept-Language': acceptLanguage, - 'Accept-Encoding': acceptEncoding, - 'Referer': baseUrl + '/', - 'Authorization': 'Bearer ' + authToken, - 'Connection': 'keep-alive', - 'TE': 'Trailers' + req = [ + { + method: 'get', + url: baseUrl + '/api/account', + params: { + cookies: { + 'XSRF-TOKEN': defaultXSRFToken, + }, + headers: { + Host: host, + 'User-Agent': userAgent, + Accept: 'application/json, text/plain, */*', + 'Accept-Language': acceptLanguage, + 'Accept-Encoding': acceptEncoding, + Referer: baseUrl + '/', + Authorization: 'Bearer ' + authToken, + Connection: 'keep-alive', + TE: 'Trailers', + }, + tags: { name: baseUrl + '/api/account' }, }, - 'tags': {'name': baseUrl + '/api/account'} - } - }]; + }, + ]; res = http.batch(req); // A new XSRF Token is needed now, we have to extract it from the cookies const xsrftoken = res[0].headers['Set-Cookie'].match('(.*XSRF-TOKEN=)([a-z0-9]+[a-z0-9\\-]+[a-z0-9]+)(;.*)')[2]; @@ -113,23 +121,23 @@ export function login(username, password) { } export function Artemis(authToken, xsrftoken) { - this.get = function(endpoint, params) { + this.get = function (endpoint, params) { return request('get', endpoint, authToken, xsrftoken, null, params); }; - this.post = function(endpoint, body, params) { + this.post = function (endpoint, body, params) { return request('post', endpoint, authToken, xsrftoken, body, params); }; - this.put = function(endpoint, body, params) { + this.put = function (endpoint, body, params) { return request('put', endpoint, authToken, xsrftoken, body, params); }; - this.delete = function(endpoint, params) { + this.delete = function (endpoint, params) { return request('delete', endpoint, authToken, xsrftoken, null, params); }; - this.websocket = function(doOnSocket) { + this.websocket = function (doOnSocket) { const websocketEndpoint = websocketProtocol + '://' + host + '/websocket/tracker/websocket'; const websocketUrl = websocketEndpoint + '?access_token=' + authToken; - ws.connect(websocketUrl, { tags: { name: websocketEndpoint } }, function(socket) { + ws.connect(websocketUrl, { tags: { name: websocketEndpoint } }, function (socket) { socket.on('open', function open() { socket.send('CONNECT\nX-XSRF-TOKEN:' + xsrftoken + '\naccept-version:1.1,1.0\nheart-beat:10000,10000\n\n\u0000'); }); diff --git a/src/test/k6/requests/user.js b/src/test/k6/requests/user.js index ec5323bd6063..bdadec601c31 100644 --- a/src/test/k6/requests/user.js +++ b/src/test/k6/requests/user.js @@ -1,7 +1,6 @@ import { USERS } from './endpoints.js'; -import {addUserToInstructorsInCourse, addUserToStudentsInCourse} from "./course.js"; -import {login} from "./requests.js"; - +import { addUserToInstructorsInCourse, addUserToStudentsInCourse } from './course.js'; +import { login } from './requests.js'; export function getUser(artemis, i, baseUsername) { const username = baseUsername.replace('USERID', i); @@ -20,12 +19,11 @@ export function updateUser(artemis, user) { } export function newUser(artemis, i, baseUsername, basePassword, studentGroupName, instructorGroupName) { - const username = baseUsername.replace('USERID', i); const password = basePassword.replace('USERID', i); - let authorities = ["ROLE_USER"]; + let authorities = ['ROLE_USER']; if (i === 1) { - authorities = ["ROLE_USER", "ROLE_INSTRUCTOR"]; + authorities = ['ROLE_USER', 'ROLE_INSTRUCTOR']; } let groups = [studentGroupName]; @@ -36,14 +34,14 @@ export function newUser(artemis, i, baseUsername, basePassword, studentGroupName const user = { login: username, password: password, - firstName: "Artemis Test " + i, - lastName: "Artemis Test " + i, - email: "testuser_"+i+"@tum.invalid", + firstName: 'Artemis Test ' + i, + lastName: 'Artemis Test ' + i, + email: 'testuser_' + i + '@tum.invalid', activated: true, - langKey: "en", + langKey: 'en', authorities: authorities, groups: groups, - createdBy: "test-case", + createdBy: 'test-case', }; console.log('Try to create new user ' + username); @@ -51,16 +49,14 @@ export function newUser(artemis, i, baseUsername, basePassword, studentGroupName if (res[0].status !== 201) { console.info('Unable to generate new user ' + username + ' (status: ' + res[0].status + ')!'); return -1; - } - else { - console.log('SUCCESS: Created new user ' + username + " with groups " + res[0].body.groups); + } else { + console.log('SUCCESS: Created new user ' + username + ' with groups ' + res[0].body.groups); } return JSON.parse(res[0].body).id; } export function updateUserWithGroup(artemis, i, baseUsername, course) { - const username = baseUsername.replace('USERID', i); addUserToStudentsInCourse(artemis, username, course.id); @@ -73,8 +69,8 @@ export function createUsersIfNeeded(artemis, baseUsername, basePassword, adminUs const shouldCreateUsers = __ENV.CREATE_USERS === true || __ENV.CREATE_USERS === 'true'; const iterations = parseInt(__ENV.ITERATIONS); - if(shouldCreateUsers) { - console.log("Try to create " + iterations + " users"); + if (shouldCreateUsers) { + console.log('Try to create ' + iterations + ' users'); for (let i = 1; i <= iterations; i++) { let userId = newUser(artemis, i, baseUsername, basePassword, course.studentGroupName, course.instructorGroupName); if (userId === -1) { @@ -82,12 +78,11 @@ export function createUsersIfNeeded(artemis, baseUsername, basePassword, adminUs updateUserWithGroup(artemis, i, baseUsername, course); } } - } - else { - console.log("Do not create users, assume the user exists in the external system, will update their groups"); + } else { + console.log('Do not create users, assume the user exists in the external system, will update their groups'); for (let i = 1; i <= iterations; i++) { // we need to login once with the user, so that the user is synced and available for the update with the groups - login(baseUsername.replace('USERID', i), basePassword.replace('USERID', i)) + login(baseUsername.replace('USERID', i), basePassword.replace('USERID', i)); } artemis = login(adminUsername, adminPassword); for (let i = 1; i <= iterations; i++) { diff --git a/src/test/k6/resource/constants_c.js b/src/test/k6/resource/constants_c.js index f80fecf88062..546d36f42605 100644 --- a/src/test/k6/resource/constants_c.js +++ b/src/test/k6/resource/constants_c.js @@ -1,4 +1,5 @@ -export const programmingExerciseProblemStatementC = '### Tests\n' + +export const programmingExerciseProblemStatementC = + '### Tests\n' + '\n' + '#### General Tasks\n' + '1. [task][0 as Input](TestInput_0)\n' + @@ -22,20 +23,22 @@ export const programmingExerciseProblemStatementC = '### Tests\n' + export const buildErrorContentC = { newFiles: [], - content: [{ - fileName: 'main.c', - fileContent: 'a' - }] + content: [ + { + fileName: 'main.c', + fileContent: 'a', + }, + ], }; -export const someSuccessfulErrorContentC= { +export const someSuccessfulErrorContentC = { newFiles: [], - content: [{ - fileName: 'main.c', - fileContent: 'int main(void) {\n' + - '\treturn 0; // Success\n'+ - '}\n' - }] + content: [ + { + fileName: 'main.c', + fileContent: 'int main(void) {\n' + '\treturn 0; // Success\n' + '}\n', + }, + ], }; export const allSuccessfulContentC = { @@ -43,83 +46,84 @@ export const allSuccessfulContentC = { content: [ { fileName: 'main.c', - fileContent: '#include // For printf(...)\n' + - '#include // For fork()\n' + - '#include // For wait(...)\n' + - '#include // strcmp(...)\n' + - '\n' + - 'int readProcessCount();\n' + - 'int createForks(int count);\n' + - 'void waitForEnd();\n' + - 'void waitPidChildren(int count);\n' + - '\n' + - 'int main(void) {\n' + - '\tint count = readProcessCount();\n' + - '\n' + - '\tint pid = createForks(count);\n' + - '\tif(pid != 0) {\n' + - '\t\twaitPidChildren(count);\n' + - '\t\tprintf("Parent with PID %i terminated.\\n", getpid());\n' + - '\t}\n' + - '\treturn 0; // Success\n' + - '}\n' + - '\n' + - 'int readProcessCount() {\n' + - '\tint count = -1;\n' + - '\tdo\n' + - '\t{\n' + - '\t\tprintf("Enter process count:\\n");\n' + - '\t\tfflush(stdout);\n' + - '\t\tif(!scanf("%i", &count)) {\n' + - '\t\t\t// Clear input if user did not enter a valid int:\n' + - '\t\t\tint c;\n' + - '\t\t\twhile ((c = getchar()) != \'\\n\' && c != EOF);\n' + - '\t\t}\n' + - '\t} while (count < 0);\n' + - '\treturn count;\n' + - '}\n' + - '\n' + - '// Recursively create new processes:\n' + - 'int createForks(int count) {\n' + - '\tif(count <= 0) { return 1;}\n' + - '\n' + - '\tint pid = fork();\n' + - '\tswitch(pid) {\n' + - '\t\tcase -1: // Error\n' + - '\t\t\tperror ("fork() failed");\n' + - '\t\t\tbreak;\n' + - '\n' + - '\t\tcase 0: // Child\n' + - '\t\t\tpid = getpid();\n' + - '\t\t\tprintf("I\'m your child! PID: %i, PPID: %i\\n", pid, getppid());\n' + - '\t\t\twaitForEnd();\n' + - '\t\t\tprintf("Child with PID %i terminated.\\n", pid);\n' + - '\t\t\treturn 0;\n' + - '\n' + - '\t\tdefault: // Parent\n' + - '\t\t\treturn createForks(--count);\n' + - '\t}\n' + - '\treturn pid;\n' + - '}\n' + - '\n' + - 'void waitForEnd() {\n' + - '\tchar buffer[1024];\n' + - '\tdo\n' + - '\t{\n' + - '\t\tif(!scanf("%s", buffer)) {\n' + - '\t\t\t// Clear input if user did not enter a valid int:\n' + - '\t\t\tint c;\n' + - '\t\t\twhile ((c = getchar()) != \'\\n\' && c != EOF);\n' + - '\t\t}\n' + - '\t\t// printf("Read: %s\\n", buffer); // Debug output\n' + - '\t} while (strcmp(buffer, "END"));\n' + - '}\n' + - '\n' + - 'void waitPidChildren(int count) {\n' + - '\tfor(int i = 0; i < count; i++) {\n' + - '\t\twaitpid(-1, NULL, 0); // Make sure we wait on the child process to prevent it from getting a Zombie process\n' + - '\t}\n' + - '}' - } - ] + fileContent: + '#include // For printf(...)\n' + + '#include // For fork()\n' + + '#include // For wait(...)\n' + + '#include // strcmp(...)\n' + + '\n' + + 'int readProcessCount();\n' + + 'int createForks(int count);\n' + + 'void waitForEnd();\n' + + 'void waitPidChildren(int count);\n' + + '\n' + + 'int main(void) {\n' + + '\tint count = readProcessCount();\n' + + '\n' + + '\tint pid = createForks(count);\n' + + '\tif(pid != 0) {\n' + + '\t\twaitPidChildren(count);\n' + + '\t\tprintf("Parent with PID %i terminated.\\n", getpid());\n' + + '\t}\n' + + '\treturn 0; // Success\n' + + '}\n' + + '\n' + + 'int readProcessCount() {\n' + + '\tint count = -1;\n' + + '\tdo\n' + + '\t{\n' + + '\t\tprintf("Enter process count:\\n");\n' + + '\t\tfflush(stdout);\n' + + '\t\tif(!scanf("%i", &count)) {\n' + + '\t\t\t// Clear input if user did not enter a valid int:\n' + + '\t\t\tint c;\n' + + "\t\t\twhile ((c = getchar()) != '\\n' && c != EOF);\n" + + '\t\t}\n' + + '\t} while (count < 0);\n' + + '\treturn count;\n' + + '}\n' + + '\n' + + '// Recursively create new processes:\n' + + 'int createForks(int count) {\n' + + '\tif(count <= 0) { return 1;}\n' + + '\n' + + '\tint pid = fork();\n' + + '\tswitch(pid) {\n' + + '\t\tcase -1: // Error\n' + + '\t\t\tperror ("fork() failed");\n' + + '\t\t\tbreak;\n' + + '\n' + + '\t\tcase 0: // Child\n' + + '\t\t\tpid = getpid();\n' + + '\t\t\tprintf("I\'m your child! PID: %i, PPID: %i\\n", pid, getppid());\n' + + '\t\t\twaitForEnd();\n' + + '\t\t\tprintf("Child with PID %i terminated.\\n", pid);\n' + + '\t\t\treturn 0;\n' + + '\n' + + '\t\tdefault: // Parent\n' + + '\t\t\treturn createForks(--count);\n' + + '\t}\n' + + '\treturn pid;\n' + + '}\n' + + '\n' + + 'void waitForEnd() {\n' + + '\tchar buffer[1024];\n' + + '\tdo\n' + + '\t{\n' + + '\t\tif(!scanf("%s", buffer)) {\n' + + '\t\t\t// Clear input if user did not enter a valid int:\n' + + '\t\t\tint c;\n' + + "\t\t\twhile ((c = getchar()) != '\\n' && c != EOF);\n" + + '\t\t}\n' + + '\t\t// printf("Read: %s\\n", buffer); // Debug output\n' + + '\t} while (strcmp(buffer, "END"));\n' + + '}\n' + + '\n' + + 'void waitPidChildren(int count) {\n' + + '\tfor(int i = 0; i < count; i++) {\n' + + '\t\twaitpid(-1, NULL, 0); // Make sure we wait on the child process to prevent it from getting a Zombie process\n' + + '\t}\n' + + '}', + }, + ], }; diff --git a/src/test/k6/resource/constants_java.js b/src/test/k6/resource/constants_java.js index 70fdfded1b36..e47c2c3776f1 100644 --- a/src/test/k6/resource/constants_java.js +++ b/src/test/k6/resource/constants_java.js @@ -1,4 +1,5 @@ -export const programmingExerciseProblemStatementJava = '# Sorting with the Strategy Pattern\n' + +export const programmingExerciseProblemStatementJava = + '# Sorting with the Strategy Pattern\n' + '\n' + 'In this exercise, we want to implement sorting algorithms and choose them based on runtime specific variables.\n' + '\n' + @@ -87,41 +88,42 @@ export const programmingExerciseProblemStatementJava = '# Sorting with the Strat export const buildErrorContentJava = { newFiles: [], - content: [{ - fileName: 'src/de/test/BubbleSort.java', - fileContent: 'a' - }] + content: [ + { + fileName: 'src/de/test/BubbleSort.java', + fileContent: 'a', + }, + ], }; export const testErrorContentJava = { newFiles: [], - content: [{ - fileName: 'src/de/test/BubbleSort.java', - fileContent: 'package de.test;\n' + - '\n' + - 'import java.util.*;\n' + - '\n' + - 'public class BubbleSort {\n' + - '\n' + - ' public void performSort(List input) {}\n' + - '}' - }] + content: [ + { + fileName: 'src/de/test/BubbleSort.java', + fileContent: + 'package de.test;\n' + '\n' + 'import java.util.*;\n' + '\n' + 'public class BubbleSort {\n' + '\n' + ' public void performSort(List input) {}\n' + '}', + }, + ], }; export const someSuccessfulErrorContentJava = { newFiles: ['src/de/test/SortStrategy.java'], - content: [{ - fileName: 'src/de/test/SortStrategy.java', - fileContent: 'package de.test;\n' + - '\n' + - 'import java.util.Date;\n' + - 'import java.util.List;\n' + - '\n' + - 'public interface SortStrategy {\n' + - '\n' + - '\tpublic void performSort(List input);\n' + - '}' - }] + content: [ + { + fileName: 'src/de/test/SortStrategy.java', + fileContent: + 'package de.test;\n' + + '\n' + + 'import java.util.Date;\n' + + 'import java.util.List;\n' + + '\n' + + 'public interface SortStrategy {\n' + + '\n' + + '\tpublic void performSort(List input);\n' + + '}', + }, + ], }; export const allSuccessfulContentJava = { @@ -129,7 +131,8 @@ export const allSuccessfulContentJava = { content: [ { fileName: 'src/de/test/Context.java', - fileContent: 'package de.test;\n' + + fileContent: + 'package de.test;\n' + '\n' + 'import java.util.Date;\n' + 'import java.util.List;\n' + @@ -163,7 +166,8 @@ export const allSuccessfulContentJava = { }, { fileName: 'src/de/test/BubbleSort.java', - fileContent: 'package de.test;\n' + + fileContent: + 'package de.test;\n' + '\n' + 'import java.util.*;\n' + '\n' + @@ -182,11 +186,12 @@ export const allSuccessfulContentJava = { '\t\t}\n' + '\n' + '\t}\n' + - '}' + '}', }, { - fileName: "src/de/test/Client.java", - fileContent: 'package de.test;\n' + + fileName: 'src/de/test/Client.java', + fileContent: + 'package de.test;\n' + '\n' + 'import java.text.*;\n' + 'import java.util.*;\n' + @@ -267,11 +272,12 @@ export const allSuccessfulContentJava = { ' private static void printDateList(List list) {\n' + ' System.out.println(list.toString());\n' + ' }\n' + - '}' + '}', }, { - fileName: "src/de/test/MergeSort.java", - fileContent: 'package de.test;\n' + + fileName: 'src/de/test/MergeSort.java', + fileContent: + 'package de.test;\n' + '\n' + 'import java.util.*;\n' + '\n' + @@ -323,11 +329,12 @@ export const allSuccessfulContentJava = { ' input.set(wholeIndex + low, temp[wholeIndex]);\n' + ' }\n' + ' }\n' + - '}' + '}', }, { fileName: 'src/de/test/Policy.java', - fileContent: 'package de.test;\n' + + fileContent: + 'package de.test;\n' + '\n' + 'public class Policy {\n' + '\t\n' + @@ -346,7 +353,7 @@ export const allSuccessfulContentJava = { '\t\t\tthis.context.setSortAlgorithm(new BubbleSort());\n' + '\t\t}\n' + '\t}\n' + - '}' - } - ] + '}', + }, + ], }; diff --git a/src/test/k6/resource/constants_python.js b/src/test/k6/resource/constants_python.js index b4db3f20f212..bfb87c809022 100644 --- a/src/test/k6/resource/constants_python.js +++ b/src/test/k6/resource/constants_python.js @@ -1,4 +1,5 @@ -export const programmingExerciseProblemStatementPython = '# Sorting with the Strategy Pattern\n' + +export const programmingExerciseProblemStatementPython = + '# Sorting with the Strategy Pattern\n' + '\n' + 'In this exercise, we want to implement sorting algorithms and choose them based on runtime specific variables.\n' + '\n' + @@ -91,28 +92,32 @@ export const programmingExerciseProblemStatementPython = '# Sorting with the Str '\n' + '2. Think about a useful decision in `Policy` when to use the new `QuickSort` algorithm.\n'; - export const buildErrorContentPython = { newFiles: [], - content: [{ - fileName: 'context.py', - fileContent: 'a' - }] + content: [ + { + fileName: 'context.py', + fileContent: 'a', + }, + ], }; export const someSuccessfulErrorContentPython = { newFiles: [], - content: [{ - fileName: 'sort_strategy.py', - fileContent: 'from abc import ABC, abstractmethod\n' + - '\n' + - '\n' + - 'class SortStrategy(ABC):\n' + - '\n' + - '\t@abstractmethod\n' + - '\tdef perform_sort(self, array):\n' + - '\t\tpass' - }] + content: [ + { + fileName: 'sort_strategy.py', + fileContent: + 'from abc import ABC, abstractmethod\n' + + '\n' + + '\n' + + 'class SortStrategy(ABC):\n' + + '\n' + + '\t@abstractmethod\n' + + '\tdef perform_sort(self, array):\n' + + '\t\tpass', + }, + ], }; export const allSuccessfulContentPython = { @@ -120,7 +125,8 @@ export const allSuccessfulContentPython = { content: [ { fileName: 'sorting_algorithms.py', - fileContent: 'from .sort_strategy import SortStrategy\n' + + fileContent: + 'from .sort_strategy import SortStrategy\n' + '\n' + '\n' + 'class BubbleSort(SortStrategy):\n' + @@ -181,7 +187,8 @@ export const allSuccessfulContentPython = { }, { fileName: 'policy.py', - fileContent: 'from .sorting_algorithms import *\n' + + fileContent: + 'from .sorting_algorithms import *\n' + '\n' + '\n' + 'class Policy:\n' + @@ -192,16 +199,16 @@ export const allSuccessfulContentPython = { '\n' + '\tdef configure(self):\n' + '\t\tif len(self.context.numbers) > 10:\n' + - '\t\t\tprint(\'More than 10 numbers, choosing merge sort!\')\n' + + "\t\t\tprint('More than 10 numbers, choosing merge sort!')\n" + '\t\t\tself.context.sorting_algorithm = MergeSort()\n' + '\t\telse:\n' + - '\t\t\tprint(\'Less or equal than 10 numbers, choosing bubble sort!\')\n' + - '\t\t\tself.context.sorting_algorithm = BubbleSort()\n' - + "\t\t\tprint('Less or equal than 10 numbers, choosing bubble sort!')\n" + + '\t\t\tself.context.sorting_algorithm = BubbleSort()\n', }, { - fileName: "context.py", - fileContent: 'package de.test;\n' + + fileName: 'context.py', + fileContent: + 'package de.test;\n' + '\n' + 'import java.text.*;\n' + 'import java.util.*;\n' + @@ -282,17 +289,17 @@ export const allSuccessfulContentPython = { ' private static void printDateList(List list) {\n' + ' System.out.println(list.toString());\n' + ' }\n' + - '}' + '}', }, { - fileName: "context.py", - fileContent: 'class Context:\n' + + fileName: 'context.py', + fileContent: + 'class Context:\n' + '\tsorting_algorithm = None\n' + '\tnumbers = None\n' + '\n' + '\tdef sort(self):\n' + - '\t\tself.sorting_algorithm.perform_sort(self.numbers)\n' - - } - ] + '\t\tself.sorting_algorithm.perform_sort(self.numbers)\n', + }, + ], }; diff --git a/src/test/k6/util/utils.js b/src/test/k6/util/utils.js index 4806ca140725..73c61a5377c1 100644 --- a/src/test/k6/util/utils.js +++ b/src/test/k6/util/utils.js @@ -13,7 +13,10 @@ export function nextAlphanumeric(length) { } export function nextWSSubscriptionId() { - return Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 12); + return Math.random() + .toString(36) + .replace(/[^a-z]+/g, '') + .substr(0, 12); } export function randomArrayValue(array) { diff --git a/src/test/resources/config/bootstrap.yml b/src/test/resources/config/bootstrap.yml deleted file mode 100644 index 11cd6af21cba..000000000000 --- a/src/test/resources/config/bootstrap.yml +++ /dev/null @@ -1,4 +0,0 @@ -spring: - cloud: - config: - enabled: false diff --git a/tsconfig.json b/tsconfig.json index 1abb362bbd15..f06880acea72 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -38,7 +38,6 @@ "src/main/webapp/app" ], "exclude": [ - "node_modules", - "src/test" + "node_modules" ] } diff --git a/tsconfig.spec.json b/tsconfig.spec.json index 3ef45db569ce..9da8414ba025 100644 --- a/tsconfig.spec.json +++ b/tsconfig.spec.json @@ -12,6 +12,6 @@ } }, "files": ["src/test/javascript/spec/entry.ts"], - "include": ["src/test/javascript/spec", "src/main/webapp/app"], + "include": ["src/test/javascript", "src/main/webapp/app"], "exclude": ["node_modules"] } diff --git a/tslint-doc.json b/tslint-doc.json index 476be9d189df..ffb43d11b3d6 100644 --- a/tslint-doc.json +++ b/tslint-doc.json @@ -7,7 +7,7 @@ ], "rules": { "completed-docs": [ - true, + false, { "enums": { "visibilities": ["all"] }, "functions": { "visibilities": ["all"] }, diff --git a/tslint.json b/tslint.json index 7df1c42e6787..278111196878 100644 --- a/tslint.json +++ b/tslint.json @@ -1,5 +1,8 @@ { - "rulesDirectory": ["node_modules/codelyzer"], + "rulesDirectory": [ + "node_modules/codelyzer", + "tslint-no-unused-expression-chai" + ], "extends": [ "tslint-config-prettier" ], @@ -42,7 +45,8 @@ "no-string-literal": false, "no-switch-case-fall-through": true, "no-trailing-whitespace": true, - "no-unused-expression": true, + "no-unused-expression-chai": true, +// "no-unused-expression": true, "no-var-keyword": true, "object-literal-sort-keys": false, "one-line": [ diff --git a/yarn.lock b/yarn.lock index 5fc6e9a76984..16ce227a53c5 100644 --- a/yarn.lock +++ b/yarn.lock @@ -5012,6 +5012,11 @@ eslint-loader@4.0.2: object-hash "^2.0.3" schema-utils "^2.6.5" +eslint-plugin-chai-friendly@^0.5.0: + version "0.5.0" + resolved "https://registry.yarnpkg.com/eslint-plugin-chai-friendly/-/eslint-plugin-chai-friendly-0.5.0.tgz#42418c35c4a83584f3b98449b7b8f4f56205a0a3" + integrity sha512-Pxe6z8C9fP0pn2X2nGFU/b3GBOCM/5FVus1hsMwJsXP3R7RiXFl7g0ksJbsc0GxiLyidTW4mEFk77qsNn7Tk7g== + eslint-plugin-prettier@3.1.3: version "3.1.3" resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.1.3.tgz#ae116a0fc0e598fdae48743a4430903de5b4e6ca" @@ -12484,7 +12489,7 @@ tsutils@^2.29.0: dependencies: tslib "^1.8.1" -tsutils@^3.17.1: +tsutils@^3.0.0, tsutils@^3.17.1: version "3.17.1" resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.17.1.tgz#ed719917f11ca0dee586272b2ac49e015a2dd759" integrity sha512-kzeQ5B8H3w60nFY2g8cJIuH7JDpsALXySGtwGJ0p2LSjLgay3NdIpqq5SoOBe46bKDW2iq25irHCr8wjomUS2g==