首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >角:从组件中测试apis

问角:从组件中测试apis
EN

Stack Overflow用户
提问于 2022-02-18 07:43:27
回答 1查看 148关注 0票数 0

我已经开始学习如何测试棱角项目。到目前为止,基本的单元测试对我来说还不错,但是对于依赖测试来说,尤其是当API服务被注入到组件中时,我面临着提供HttpClient的问题。我尝试过不同的解决方案,但没有一个对我有帮助。

服务

代码语言:javascript
复制
// Present in HttpClientService file
getDisposition() {
  return this.http.get<{ message: string, data: { dispositionList: Disposition[] } }>(`${this.URL}/disposition/get`);
}

// Present in FileProcessService file
deleteMedia(media: string) {
    return this.http.delete<{ message: string }>(`${this.URL}/certificate/delete?certificate=${media}`);
}

add-edit-activity.component.ts

代码语言:javascript
复制
import { HttpEventType } from '@angular/common/http';
import { Component, ElementRef, Inject, OnInit, ViewChild } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { DomSanitizer, SafeUrl } from '@angular/platform-browser';
import { AssignedPerson } from '@model/assigned-person.model';
import { Disposition } from '@model/disposition.model';
import { mimeTypes } from '@model/mime-type';
import { FileProcessService } from '@service/file-process.service';
import { HttpClientService } from '@service/http-client.service';
import { DeleteComponent } from '@shared/delete/delete.component';
import { CustomErrorStateMatcher } from '@validator/error-state-matcher';
import { ToastrService } from 'ngx-toastr';

@Component({
  selector: 'app-add-edit-activity',
  templateUrl: './add-edit-activity.component.html',
  styleUrls: ['./add-edit-activity.component.css']
})
export class AddEditActivityComponent implements OnInit {

  constructor(private fb: FormBuilder, private sanitizer: DomSanitizer, private dialogRef: MatDialogRef<AddEditActivityComponent>, @Inject(MAT_DIALOG_DATA) public data: any,
    private _http: HttpClientService, private _fileService: FileProcessService, private toastr: ToastrService, private dialog: MatDialog,) { }

  re = new RegExp(/^[a-zA-Z-]*/, 'g');
  ISOstamp = { T: ' ', Z: '000' };
  matcher = new CustomErrorStateMatcher();
  dispositionList: Disposition[] = [];
  assignedPersonList: AssignedPerson[] = [];
  filterAssignedPersonList: AssignedPerson[] = [];
  uploaded = false;
  uploadProgress = false;
  fileURL: SafeUrl;
  activityForm = this.fb.group({
    gaugeId: [this.data.gaugeId, Validators.maxLength(9)], createTimeStamp: [{ value: new Date().toISOString().replace(/[TZ]/g, m => this.ISOstamp[m]), disabled: true }],
    user: [{ value: sessionStorage.getItem('username'), disabled: true }], disposition: ['', [Validators.required, Validators.maxLength(30)]],
    assignedPersonName: ['', Validators.maxLength(30)], department: ['', Validators.maxLength(20)],
    shift: ['', Validators.maxLength(1)], remark: ['', Validators.maxLength(50)],
    calibrationDate: ['', Validators.maxLength(10)], attachment: ['', Validators.maxLength(255)]
  });

  @ViewChild('file') certificate: ElementRef;

  ngOnInit(): void {
    this.data.type.match(this.re)[0] === 'Update' && this.setFormValues();
    this._http.getDisposition().subscribe(response => this.dispositionList = response.data.dispositionList);
    this._http.getAssignedPerson().subscribe(response => this.assignedPersonList = this.filterAssignedPersonList = response.data.assignedToList);
  }

  get GaugeId() {
    return this.activityForm.get('gaugeId');
  }

  get TimeStamp() {
    return this.activityForm.get('createTimeStamp');
  }

  get Attachment() {
    return this.activityForm.get('attachment');
  }

  get Disposition() {
    return this.activityForm.get('disposition');
  }

  get DispositionValue() {
    return this.dispositionList.map(e => e.dispositionType).indexOf(this.Disposition.value) < 0;
  }

  get AssignedTo() {
    return this.activityForm.get('assignedPersonName');
  }

  get AssignedToValue() {
    return this.assignedPersonList.map(e => `${e.firstName} ${e.lastName}`).indexOf(this.Disposition.value) < 0;
  }

  private async setFormValues() {
    this.activityForm.patchValue({ ...this.data });
    if (this.data.attachment) {
      this.uploadProgress = true;
      this.uploaded = true;
      await this.fetchUploadedFile(this.data.attachment, mimeTypes[this.data.attachment.split('.')[1]]);
      this.activityForm.markAsPristine();
    }
  }

  searchAssignedPerson(event) {
    if (event.target.value) {
      this.filterAssignedPersonList = [];
      for (let person of this.assignedPersonList) {
        if (person.firstName.toLowerCase().startsWith(event.target.value.toLowerCase())) {
          this.filterAssignedPersonList.push(person);
        }
      }
    } else { this.filterAssignedPersonList = this.assignedPersonList }
  }

  upload(event) {
    const file: File = event.target.files[0];
    this.certificate.nativeElement.value = '';
    if (file.size > (20 * 1000 * 1000)) { // Checking if File size is above 20MB
      this.toastr.error('Size of ' + file.name + ' is above 20MB');
      return;
    }
    const fd = new FormData();
    fd.append('certificate', file, file.name);
    this.processAttachment(fd);
  }

  private processAttachment(file: FormData) {
    this._fileService.uploadMedia(file).subscribe(event => {
      if (event.type === HttpEventType.UploadProgress) { this.uploadProgress = true }
      if (event.type === HttpEventType.Response) {
        let media = event.body.data.Certificate;
        this.fetchUploadedFile(media.fileName, media.fileType);
        this.toastr.info(event.body.message);
      }
    }, error => {
      this.toastr.error(error.error.message);
      this.uploadProgress = false;
    });
  }

  private async fetchUploadedFile(file: string, mimeType: string) {
    try {
      let response = await this._fileService.getMedia(file).toPromise();
      this.fileURL = this.sanitizer.bypassSecurityTrustUrl(URL.createObjectURL(new Blob([response], { type: mimeType })));
      this.uploaded = true;
      this.uploadProgress = false;
      this.activityForm.patchValue({ attachment: file });
      this.Attachment.markAsDirty();
    } catch (error) {
      this.uploadProgress = false;
      this._fileService.processError(error.error)
    }
  }

  deleteFile() {
    this.dialog.open(DeleteComponent, {
      width: '350px', disableClose: true
    }).afterClosed().subscribe(response => {
      if (response) {
        this._fileService.deleteMedia(this.Attachment.value).subscribe(response => {
          this.toastr.info(response.message);
          this.activityForm.patchValue({ attachment: '' });
          this.Attachment.markAsDirty();
          this.uploaded = false;
        }, error => this.toastr.error(error.error.message));
      }
    });
  }

  async doAction() {
    let message = '';
    if (this.data.type.match(this.re)[0] === 'Add') {
      message = await (await this._http.addActivityLog(this.activityForm.getRawValue()).toPromise()).message;
    } else {
      message = await (await this._http.updateActivityLog(this.GaugeId.value, this.TimeStamp.value, this.activityForm.getRawValue()).toPromise()).message;
    }
    this.dialogRef.close(message);
  }
}

add-edit-activity.component.spec.ts

代码语言:javascript
复制
import { ComponentFixture, TestBed, tick } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FileProcessService } from '@service/file-process.service';
import { HttpClientService } from '@service/http-client.service';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { AddEditActivityComponent } from './add-edit-activity.component';

describe('AddEditActivityComponent', () => {
  let component: AddEditActivityComponent;
  let fixture: ComponentFixture<AddEditActivityComponent>;
  let _http: HttpClientService, _file: FileProcessService;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AddEditActivityComponent],
      imports: [FormsModule, ReactiveFormsModule],
      providers: [
        { provide: MatDialogRef, useValue: {} },
        { provide: MAT_DIALOG_DATA, useValue: { type: 'Add Activity Log', gaugeId: 'W-001' } },,
        { provider: HttpClientService, useValue: null },
        { provider: FileProcessService, useValue: null }
      ]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AddEditActivityComponent);
    component = fixture.debugElement.componentInstance;
    _http = fixture.debugElement.injector.get(HttpClientService);
    _file = fixture.debugElement.injector.get(FileProcessService);
    fixture.detectChanges();
  });
  
  // These 2 tests throwing error.
  it('SHOULD mock http service', () => {
    let spy = spyOn(_http, 'getDisposition').and.callFake(() => {
      return of({
        message: '',
        data: { dispositionList: [] }
      }).pipe(delay(100));
    });
    component.ngOnInit();
    tick(100);
    expect(component.dispositionList).toEqual([]);
  });

  it('SHOULD mock file service', () => {
    let spy = spyOn(_file, 'deleteMedia').and.callFake((file: string) => {
      return of({ message: '' }).pipe(delay(100));
    });
    component.deleteFile();
    tick(100);
    expect(component.uploaded).toBe(false);
  });
});

这两个测试的错误(我提供了一个测试用例的错误,第二个测试用例也是一样的):

  1. 应否模拟http服务AddEditActivityComponent错误: NgModule 'DynamicTestModule‘的无效提供程序-只允许提供程序和类型的实例,获取:.、?未定义的?、.、.(node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:240:1) at providerToFactory (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11550:1) at providerToRecord (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11521:1) at R3Injector.processProvider (node_modules/@angular/core/ivy_ngcc/fesm2015/core.js:11424:1)错误::无法为getDisposition()用法找到监视对象: spyOn(,)错误::无法找到监视getDisposition()用法的对象: spyOn(,) at

任何人,请帮助我的测试用例到底发生了什么错误?被困在这里快两天了。

EN

回答 1

Stack Overflow用户

发布于 2022-02-27 14:25:07

在TestBed中提供服务时,您必须避免使用“null”值,这是导致您的问题的原因。

模拟棱角服务的最佳方法是创建SpyObj实例,然后像使用角度测试文档那样使用它们。

如果您使用的是SpyObj,下面是您的规范文件:

代码语言:javascript
复制
import { ComponentFixture, TestBed, tick } from '@angular/core/testing';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
import { FileProcessService } from '@service/file-process.service';
import { HttpClientService } from '@service/http-client.service';
import { of } from 'rxjs';
import { delay } from 'rxjs/operators';
import { AddEditActivityComponent } from './add-edit-activity.component';

describe('AddEditActivityComponent', () => {
  let component: AddEditActivityComponent;
  let fixture: ComponentFixture<AddEditActivityComponent>;
  let httpSpy: jasmine.SpyObj<HttpClientService>;
  let fileSpy: jasmine.SpyObj<FileProcessService>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [AddEditActivityComponent],
      imports: [FormsModule, ReactiveFormsModule],
      providers: [
        { provide: MatDialogRef, useValue: {} },
        { provide: MAT_DIALOG_DATA, useValue: { type: 'Add Activity Log', gaugeId: 'W-001' } },
        {
          provider: HttpClientService,
          useValue: jasmine.createSpyObj('HttpClientService', ['getDisposition', 'getAssignedPerson', 'addActivityLog', 'updateActivityLog'])
        },
        {
          provider: FileProcessService,
          useValue: jasmine.createSpyObj('FileProcessService', ['uploadMedia', 'getMedia', 'deleteMedia', 'processError'])
        }
      ]
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(AddEditActivityComponent);
    component = fixture.debugElement.componentInstance;
    httpSpy = fixture.debugElement.injector.get(HttpClientService) as jasmine.SpyObj<HttpClientService>;
    fileSpy = fixture.debugElement.injector.get(FileProcessService) as jasmine.SpyObj<FileProcessService>;
    fixture.detectChanges();
  });
  
  // These 2 tests throwing error.
  it('SHOULD mock http service', () => {
    httpSpy.getDisposition.and.callFake(() => {
      return of({
        message: '',
        data: { dispositionList: [] }
      }).pipe(delay(100));
    });
    component.ngOnInit();
    tick(100);
    expect(component.dispositionList).toEqual([]);
  });

  it('SHOULD mock file service', () => {
    fileSpy.deleteMedia.and.callFake((file: string) => {
      return of({ message: '' }).pipe(delay(100));
    });
    component.deleteFile();
    tick(100);
    expect(component.uploaded).toBe(false);
  });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71169935

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档