2016-11-10 73 views
1

我正在使用ng2-file-upload。如何在单元测试中模拟它的FileUploader类?Angular 2.0.0 - 模拟文件上传器

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

我有一个艰难的时间在我的规格嘲笑它。请帮忙。

+0

我遇到了同样的问题,我已经构建了一个文件上传组件,并试图将此https://www.noppanit.com/javascript-tdd-on-file-upload/移植到我的规范中。 TS。我刚刚在另一个资源中看到spyOn只有在您输入茉莉花时才可用。在设置的过程中。我会告诉你(我认为spyOn是解决方案)。 –

+0

@TerryBarriff谢谢。我也有一个测试它的问题,因为我已经覆盖了一些ng2-file-upload FileUploader函数。你有什么想法吗? – xiotee

+0

你检查了我的答案吗?它有帮助吗? –

回答

0

我会回复你的评论,但我觉得有以下可能有助于回答关于如何嘲笑他们的单元测试从文件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的情况下,我相信会填充文件列表,以便检查测试文件是否已导入到该文件列表中。

祝你好运!

+0

@terrybariff由于我覆盖了FileUploader的功能,所以我仍然遇到问题。我如何测试它们?我会更新这个问题。 – xiotee