输入[type =“ file”]的Angular和Jasmine单元测试更改事件

时间:2018-08-22 15:52:06

标签: angular typescript unit-testing jasmine

我正在尝试100%的测试覆盖率,但是我似乎无法测试此onUploadFile函数中的内容。

```html模板

<input type="file" formControlName="theUpload" id="upload" (change)="onUploadFile($event, i, true)">

```filing.ts文件

onUploadFile(evt: Event, index: number, isReq: boolean = false): void {
  const reader = new FileReader();
  const target = <HTMLInputElement>evt.target;

  if (target.files && target.files.length) {
    const file = target.files[0];
    reader.readAsDataURL(file);
    reader.onload = () => {
      this.getUploadFormGroup(index, isReq).patchValue({
        filename: file.name,
        filetype: file.type,
        value: reader.result.split(',')[1],
        dateUploaded: new Date()
      });

      console.log(
        `getUploadFormArray (${isReq ? 'required' : 'other'} forms)`,
        this.getUploadFormArray(isReq)
      );
    };
  }
}

```filing.spec.ts文件

it('should call onUploadFile when input is changed for required files', () => {
  spyOn(component, 'onUploadFile').and.callThrough();

  const fakeChangeEvent = new Event('change');

  const targ = <HTMLInputElement>de.nativeElement.querySelector('input#upload');
  targ.dispatchEvent(fakeChangeEvent);

  fixture.whenStable().then(() => {
    expect(component.onUploadFile).toHaveBeenCalledWith(fakeChangeEvent, 0, true);
    expect(targ.files.length).toBeGreaterThan(0); //  this is always zero because i can't add to targ.files (readonly FileList)
  });
});

我愿意嘲笑任何可以嘲笑的东西,但是有人可以告诉我如何测试console.log函数(要求我在target.files数组中至少有一项吗?

1 个答案:

答案 0 :(得分:2)

让我们遵循 divide and conquer 规则-由于单元测试的目的是分别测试组件逻辑的各个部分,因此我将稍作更改以简化单元测试的组件逻辑

您正在onload方法中为onUploadFile设置匿名回调函数,因此无法对其进行监视。作为权衡,您可以重构回调方法:

export class TestComponent {
  ...
  getLoadCallback(fg: FormGroup, file: File, reader: FileReader): () => void {
    return () => {
      fg.patchValue({
        filename: file.name,
        filetype: file.type,
        value: reader.result.split(',')[1],
        dateUploaded: new Date()
      });

      // do some other stuff here
    };
  }

  onUploadFile(evt: Event, index: number, isReq: boolean = false): void {
    const reader = new FileReader();
    const target = <HTMLInputElement>evt.target;

    if (target.files && target.files.length) {
      const file = target.files[0];
      reader.readAsDataURL(file);
      const fg = this.getUploadFormGroup(index, isReq);
      reader.onload = this.getLoadCallback(fg, file, reader);
    }
  }
  ...
}

因此,现在我们至少可以创建三个单元测试:一个用于在输入事件上触发onUploadFile(您现有的测试对此很有用),另一个用于测试getLoadCallback方法,最后-用于onUploadFile方法:

  it('getLoadCallback', () => {
    const mockValue = ['a', 'b'];
    const result = jasmine.createSpyObj('result', ['split']);
    result.split.and.callFake(() => mockValue);
    const mockReader = { result } as FileReader;
    const mockFormGroup: FormGroup = jasmine.createSpyObj('FormGroup', ['patchValue']);
    const mockFile = new File([''], 'filename', { type: 'text/html' });
    const callback: () => void = component.getLoadCallback(mockFormGroup, mockFile, mockReader);

    callback();

    const obj = {
      filename: mockFile.name,
      filetype: mockFile.type,
      value: mockValue[1],
      dateUploaded: new Date()
    }
    expect(mockFormGroup.patchValue).toHaveBeenCalledWith(obj);
  });

  it('onUploadFile', () => {
    const mockIndex = 1;
    const mockIsReq = false;
    const mockFile = new File([''], 'filename', { type: 'text/html' });
    const mockFormGroup = new FormGroup({});
    const mockEvt = { target: { files: [mockFile] } };
    const mockReader: FileReader = jasmine.createSpyObj('FileReader', ['readAsDataURL', 'onload']);
    spyOn(window as any, 'FileReader').and.returnValue(mockReader);
    spyOn(component, 'getUploadFormGroup').and.returnValue(mockFormGroup);
    spyOn(component, 'getLoadCallback').and.callThrough();

    component.onUploadFile(mockEvt as any, mockIndex, mockIsReq);

    expect((window as any).FileReader).toHaveBeenCalled();
    expect(mockReader.readAsDataURL).toHaveBeenCalledWith(mockFile);
    expect(component.getUploadFormGroup).toHaveBeenCalledWith(mockIndex, mockIsReq);
    expect(component.getLoadCallback).toHaveBeenCalledWith(mockFormGroup, mockFile, mockReader);
  });

您当然可以更改模拟值并创建更多的单元测试...