I am doing unit testing using angular 2 when i do unit testing it show me error cannot read property 'snapshot' undefined.
ReadMailComponent should create
TypeError: Cannot read property 'snapshot' of undefined
TypeError: Cannot read property 'snapshot' of undefined
at ReadMailComponent.getCommentId (webpack:///D:/Zool-Projects/mindspark/src/app/modules/my-mindspark/components/read-mail/read-mail.component.ts?:48:27)
at ReadMailT1Component.ReadMailT2Component.ngOnInit (webpack:///D:/Zool-Projects/mindspark/src/app/shared/components/my-mindspark/read-mail/read-mail-t2/read-mail-t2.component.ts?:34:49)
at checkAndUpdateDirectiveInline (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:11043:19)
at checkAndUpdateNodeInline (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:12541:20)
at checkAndUpdateNode (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:12484:16)
at debugCheckAndUpdateNode (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:13341:59)
at debugCheckDirectivesFn (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:13282:13)
at Object.eval [as updateDirectives] (ng:///DynamicTestModule/ReadMailComponent.ngfactory.js:16:5)
at Object.debugUpdateDirectives [as updateDirectives] (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:13267:21)
at checkAndUpdateView (webpack:///D:/Zool-Projects/mindspark/node_modules/@angular/core/@angular/core.es5.js?:12451:14)
Here is readmail.component.spec.ts
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { DebugElement } from '@angular/core';
import { ReadMailComponent } from './read-mail.component';
import { ReadMailT1Component } from '../../../../shared/components/my-
mindspark/read-mail/read-mail-t1/read-mail-t1.component';
import { ReadMailT2Component } from '../../../../shared/components/my-mindspark/read-mail/read-mail-t2/read-mail-t2.component';
import { ShortenPipe } from 'ngx-pipes/src/app/pipes/string/shorten';
import { NgbModule, NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { MomentModule } from 'angular2-moment/moment.module';
import { SanitizeCodePipe } from '../../../../shared/pipes/sanitize/sanitizeCode.pipe';
import { GetFileNamePipe } from '../../../../shared/pipes/getFileName/getFileName.pipe';
import { ReactiveFormsModule } from '@angular/forms';
import { TranslateService, TranslateModule } from 'ng2-translate';
import { RouterTestingModule } from '@angular/router/testing';
import { CommentModalService } from '../../../../shared/components/comments/comment-modal/comment-modal.service';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { SharedService } from '../../../../shared/shared.service';
import { MailboxService } from '../mailbox/mailbox.service';
import { ContentService } from '../../../../shared/services/content/content.service';
import { ActivatedRoute, ActivatedRouteSnapshot } from '@angular/router';
describe('ReadMailComponent', () => {
let component: ReadMailComponent;
let fixture: ComponentFixture<ReadMailComponent>;
let activatedRoute: ActivatedRouteSnapshot;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ReadMailComponent, ReadMailT1Component, ReadMailT2Component, ShortenPipe, SanitizeCodePipe, GetFileNamePipe],
imports: [TranslateModule.forRoot(), NgbModule.forRoot(), MomentModule, ReactiveFormsModule, RouterTestingModule, HttpClientModule],
providers: [TranslateService, CommentModalService, SharedService, MailboxService, ContentService, { provide: ActivatedRoute, useValue: activatedRoute }]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ReadMailComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
Here is my readmail.component.ts file
import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { CommentModalService } from '../../../../shared/components/comments/comment-modal/comment-modal.service';
import { SharedService } from '../../../../shared/shared.service';
import { ContentService } from '../../../../shared/services/content/content.service';
import { MailboxService } from '../mailbox/mailbox.service';
import { AppSettings } from '../../../../settings/app.settings';
import * as _ from 'lodash';
@Component({
selector: 'ms-read-mail',
templateUrl: './read-mail.component.html',
styleUrls: ['./read-mail.component.scss']
})
export class ReadMailComponent implements OnInit {
template: string;
readmail: any;
errorInfo: any;
constructor(private route: ActivatedRoute, private commentModalService: CommentModalService, private mailBoxService: MailboxService,
private sharedService: SharedService, private contentService: ContentService) {
this.sharedService.setSiteTitle('ReadMail');
this.contentService.getTemplate().subscribe(
result => {
this.template = this.contentService.getTemplateId(result);
},
responseError => this.errorInfo = responseError
);
}
ngOnInit() { }
getMessageTrailData(messageID) {
/* check if messaege id not empty, else show error in an alert and return to mailbox */
this.sharedService.showLoader();
this.mailBoxService.getMessageTrailData(messageID).subscribe(
result => {
const status = this.contentService.validateResponse(result, messageID);
if (status === 'success') {
this.readmail = result;
this.contentService.setTemplate(result);
this.contentService.setBasicData(result);
}
this.sharedService.hideLoader();
},
responseError => this.errorInfo = this.sharedService.handleResponseError(responseError)
);
}
getCommentId() {
return this.route.snapshot.url[1].path;
}
showQuestion(showQue) {
return (showQue === 'SHOW') ? 'HIDE' : 'SHOW';
}
updateSelectedFiles(attachFile) {
const files = [];
if (attachFile) {
const file = attachFile.nativeElement;
if (file.files && file.files[0]) {
const uploadFile = file.files;
for (let i = 0; i < uploadFile.length; i++) {
const thisFile = uploadFile[i];
files.push({ filename: thisFile.name });
}
}
}
return files;
}
removeFile(attachFile) {
if (attachFile) {
attachFile.nativeElement.value = '';
}
return [];
}
saveCommentRating(rating, commentId) {
this.sharedService.showLoader();
const data = {
'rating': rating,
'commentID': commentId
};
this.mailBoxService.saveRating(data).subscribe(
result => {
const status = this.contentService.validateResponse(result, data);
if (status === 'success') {
console.log('Rating updated.');
}
this.sharedService.hideLoader();
},
responseError => this.errorInfo = this.sharedService.handleResponseError(responseError)
);
}
replyToMessage(replyMessage, messageID, attachFile) {
this.sharedService.showLoader();
let uploadFileError = '';
let uploadFileState = '';
const maxFileUpload = AppSettings.MAX_IMAGE_SIZE;
const formData = new FormData();
if (attachFile) {
const file = attachFile.nativeElement;
if (file.files && file.files[0]) {
const uploadFile = file.files;
for (let i = 0; i < uploadFile.length; i++) {
const thisFile = uploadFile[i];
if (thisFile.type.indexOf('image') !== 0) {
uploadFileState = 'invalidType';
} else {
const fileSize = thisFile.size / 1024;
if (fileSize > maxFileUpload * 1024) {
uploadFileState = 'fileSize';
}
}
}
if (uploadFileState === '') {
for (let i = 0; i < uploadFile.length; i++) {
formData.append('attachments[]', uploadFile[i]);
}
} else if (uploadFileState === 'invalidType') {
const acceptedTypes = AppSettings.IMAGE_FORMAT.join(' or ');
uploadFileError = 'Upload only files of type ' + acceptedTypes + '.';
} else if (uploadFileState === 'fileSize') {
uploadFileError = 'File size should not be greater than ' + maxFileUpload + 'MB.';
}
if (uploadFileError !== '') {
setTimeout(() => uploadFileError = '', 3000);
}
} else {
console.log('No file selected.');
}
}
if (uploadFileState === '') {
formData.append('replyBody', replyMessage.value.replyBody);
formData.append('messageID', messageID);
this.commentModalService.replyToMessage(formData).subscribe(
result => {
const status = this.contentService.validateResponse(result, {});
if (status === 'success') {
this.getMessageTrailData(messageID);
}
this.sharedService.hideLoader();
},
responseError => this.errorInfo = this.sharedService.handleResponseError(responseError)
);
return { result: 'success', message: '' };
} else {
this.sharedService.hideLoader();
return { result: 'error', message: uploadFileError };
}
}
open(imageBoxModal, fileName) {
this.sharedService.open(imageBoxModal);
return fileName;
}
disableSend(replyMessage) {
return replyMessage.invalid;
}
}
Here is my readmail.component.html file
<ng-container [ngSwitch]="template">
<ng-container *ngSwitchCase="'1'">
<ms-read-mail-t1 [readMail]="readmail"></ms-read-mail-t1>
</ng-container>
<ng-container *ngSwitchCase="'2'">
<ms-read-mail-t2 [readMail]="readmail"></ms-read-mail-t2>
</ng-container>
<ng-container *ngSwitchDefault>
<ms-read-mail-t1 [readMail]="readmail"></ms-read-mail-t1>
</ng-container>
</ng-container>
I think the error is coming from the url[1].path as it shows that path is undefined means that url is causing error.
I have tried all sorts of example but did not work for me please help me out. Thanks in advance
I found the solution after some R&D and the answer is that you have to provide url of snapshot in useValue of provide ActivatedRoute and here is the code
{
provide: ActivatedRoute,
useValue:
{
snapshot:
{
url: [{ path: 1 }, { path: 2 }]
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With