上传png文件的单元测试

Unit test for uploading a png file

我是单元测试的初学者,我想测试我的打字稿方法 onSelect,它允许用户 select 仅图像、pdf 和 word 文件。这是我的打字稿方法:

 addedfiles : Array<any> = [];
 fileRestrictions: FileRestrictions = {
  allowedExtensions: ['.jpg', '.png', '.jpeg', '.doc', '.docx','.pdf'],
   maxFileSize: 5000000
  };
public onSelect(ev: any): void {
  ev.files.forEach((file: FileInfo) => {
 
  if (file.rawFile) {
    const reader = new FileReader();
    if(this.fileRestrictions.allowedExtensions.includes(file.extension.toLowerCase()))
    {reader.onloadend = () => {
      this.addedfiles.push({ ...file, src: reader.result as string });
    };
    reader.readAsDataURL(file.rawFile);
    console.log(this.addedfiles)
    }
    }
   });
   }

我想编写一个单元测试来测试此方法是否允许用户 select png 文件。所以我创建了这个单元测试:

it('should select a png file', () => {

  const ev = { prevented : false , files : [{uid : '01', name : 'filename', extension : 'png' 
  , size : 123000 }]};

  component.onSelect(ev);

  expect(component.addedfiles.length).toEqual(1);

} )

它给我错误:Expected 0 to equal 1!谁能帮帮我?

由于reader.onloadend = () => {...}是私有函数,所以无法测试。 你最好使用reader.addEventListener('loadend', () => {...})。所以我们可以模拟 addEventListener 方法。

此外,Array.prototype.includes()是完全匹配,你的测试数据extension: 'png'应该是extension: '.png'。并且,您的测试数据未命中 rawFile 属性.

使用 angular v11+ 的工作示例:

example.component.ts:

import { Component } from '@angular/core';

type FileRestrictions = any;
type FileInfo = any;

@Component({})
export class ExampleComponent {
  addedfiles: Array<any> = [];
  fileRestrictions: FileRestrictions = {
    allowedExtensions: ['.jpg', '.png', '.jpeg', '.doc', '.docx', '.pdf'],
    maxFileSize: 5000000,
  };
  public onSelect(ev: any): void {
    ev.files.forEach((file: FileInfo) => {
      if (file.rawFile) {
        const reader = new FileReader();
        if (
          this.fileRestrictions.allowedExtensions.includes(
            file.extension.toLowerCase()
          )
        ) {
          console.log(reader);
          reader.addEventListener('loadend', () => {
            this.addedfiles.push({ ...file, src: reader.result as string });
          });
          reader.readAsDataURL(file.rawFile);
          console.log(this.addedfiles);
        }
      }
    });
  }
}

example.component.spec.ts:

import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { ExampleComponent } from './example.component';

fdescribe('65356063', () => {
  let fixture: ComponentFixture<ExampleComponent>;
  let component: ExampleComponent;
  beforeEach(
    waitForAsync(() => {
      TestBed.configureTestingModule({
        declarations: [ExampleComponent],
      })
        .compileComponents()
        .then(() => {
          fixture = TestBed.createComponent(ExampleComponent);
          component = fixture.componentInstance;
        });
    })
  );

  it('should select a png file', () => {
    const ev = {
      prevented: false,
      files: [
        {
          uid: '01',
          name: 'filename',
          extension: '.png',
          size: 123000,
          rawFile: 'test raw file',
        },
      ],
    };

    const mockReader = {
      addEventListener: jasmine.createSpy().and.callFake((event, listener) => {
        listener();
      }),
      readAsDataURL: jasmine.createSpy(),
    };
    spyOn(window, 'FileReader').and.returnValue(
      (mockReader as unknown) as FileReader
    );

    component.onSelect(ev);

    expect(component.addedfiles.length).toEqual(1);
    expect(mockReader.addEventListener).toHaveBeenCalledOnceWith(
      'loadend',
      jasmine.any(Function)
    );
    expect(mockReader.readAsDataURL).toHaveBeenCalledOnceWith('test raw file');
  });
});

测试结果: