Angular 2.0.0 - 模拟文件上传器

时间:2016-11-10 14:33:46

标签: unit-testing angular karma-jasmine

我正在使用ng2-file-upload。如何在单元测试中模拟其FileUploader类?

import { FileUploader } from 'ng2-file-upload/ng2-file-upload';

@Component({
  selector: 'my-component',
  template: '...',
  providers: [ MyService ]
})

export class MyComponent {
  public uploader: FileUploader = new FileUploader({url: '/my-app/api/upload',
              authToken: 'token'});
constructor() {
  this.uploader.onCompleteItem = (item:any, response: any, headers: any) => {
    console.log('how to test here');
  }
}

我很难在我的规范中嘲笑它。请帮忙。

1 个答案:

答案 0 :(得分:1)

我将回复您的评论,但我认为以下内容可能有助于回答您关于如何从文件file-drop.directive.spec.ts模拟从单元测试中获取的FileUploader类的原始问题:

import { Component } from '@angular/core';
import { inject, ComponentFixture, TestBed } from '@angular/core/testing';

import { FileUploader } from './file-uploader.class';
import { FileUploadModule } from './file-upload.module';

@Component({
  selector: 'container',
  template: `<input type="file" ng2FileSelect [uploader]="uploader" />`
})
export class ContainerComponent {
  public uploader:FileUploader = new FileUploader({url: 'localhost:3000'});
}

describe('Directive: FileSelectDirective', () => {

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FileUploadModule],
      declarations: [ContainerComponent],
      providers: [ContainerComponent]
    });
  });

  it('should be fine', inject([ContainerComponent], (fixture:ComponentFixture<ContainerComponent>) => {
    expect(fixture).not.toBeNull();
  }));
});

import { FileUploader } from './file-uploader.class';是将FileUploader导入测试的方式,ContainerComponent会导入测试本身。

除此之外,我已经创建了一个虚拟文件来测试我的组件,但我仍在编写它!

it('should accept a file for upload', () => {
    var modifiedDate = new Date();
    var file = new File([3555], 'test-file.jpg', {lastModified : modifiedDate, type: 'image/jpeg'});
    FileUploadComponent.upload(file);
});

为了测试这是否有效,我有一个元数据模型,我期望在选择的文件上填充它。因此,我可以做两个断言,上传输入框都有一个文件,并且元数据对象将被填充。

在ng2-file-upload的情况下,我相信将填充文件列表,允许您检查测试文件是否已导入到该文件中。

祝你好运!