我在做单元测试时正在使用angular 2进行单元测试,它向我显示错误无法读取未定义的属性“快照”。

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)


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();
  });
});

这是我的 readmail.component.ts 文件
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;
  }

}

这是我的 readmail.component.html 文件
<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>

我认为错误来自url [1] .path,因为它表明path未定义意味着url导致了错误。

我尝试了各种示例,但对我没有用,请帮助我。
提前致谢

最佳答案


{
        provide: ActivatedRoute,
        useValue:
            {
              snapshot:
                {
                url: [{ path: 1 }, { path: 2 }]
                 }
            }
    }

关于angular - TypeError : Cannot read property 'snapshot' of undefined failure while performing unit testing in angular2,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47430280/

10-16 19:24