首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在角7(或2+)中编写文件上传方法的单元测试

如何在角7(或2+)中编写文件上传方法的单元测试
EN

Stack Overflow用户
提问于 2019-03-26 11:31:00
回答 2查看 18.3K关注 0票数 10

我试图在角7中为文件上传方法编写单元测试。在测试窗口中获得以下错误。我刚开始做角度单元测试。有人能帮忙吗,如何添加模拟文件以获得完整的代码覆盖率?

TypeError:无法设置未定义的属性值

这是我的单元测试代码(规范文件),

代码语言:javascript
复制
describe('ImportComponent', () => {
    let component: ImportComponent;
    let fixture: ComponentFixture<ImportComponent>;
    let element;

    beforeEach(
        async(() => {
            TestBed.configureTestingModule({
                imports: [ HttpClientModule, RouterTestingModule ],
                declarations: [ ImportComponent ]
            }).compileComponents();
        })
    );

    beforeEach(() => {
        fixture = TestBed.createComponent(ImportComponent);
        component = fixture.componentInstance;
        element = fixture.nativeElement;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });

    it('should upload the file', () => {
        component.importFile();
        const inputEl = element.querySelector('#postal_file');
        const fileList = { 0: { name: 'foo', size: 500001 } };
        inputEl.value = {
            target: {
                files: fileList
            }
        };
        inputEl.dispatchEvent(new Event('change'));     
    });
});

方法在组件中。

代码语言:javascript
复制
importFile() {
        const inputEl: HTMLInputElement = this.el.nativeElement.querySelector('#postal_file');
        const fileCount: number = inputEl.files.length;
        const formData = new FormData();
        if (fileCount > 0) {
            formData.append(this.postalFileName, inputEl.files.item(0));
            this.postalService.importPostalCodes(formData).subscribe((data) => {
                this.result = data;
            });
        }
    }

以及HTML,

代码语言:javascript
复制
<div class="file-import">
        <form action="" method="post" encType="multipart/form-data">
            <label for="postal_file">Choose File</label>
            <input type="file" name="postal_file" id="postal_file">
            <button type="button" (click)="importFile()">Import</button>
        </form>
    </div>

单元测试没有涵盖所有代码,如下图所示,请帮助,如何查看100%的代码覆盖率。

代码覆盖图像

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-07-24 05:57:47

一种测试文件上传和检查模型值集的简单方法。

.html

代码语言:javascript
复制
<input (change)="onFileSelected()" #fileInput type="file" id="file">

.ts

代码语言:javascript
复制
uploadedFile : any

onFileSelected() {
  const inputNode: any = document.querySelector('#file');
  this.uploadedFile  = inputNode.files[0];
}

spec.ts

代码语言:javascript
复制
it('should detect file input change and set uploadedFile  model', () => {
    const dataTransfer = new DataTransfer()
    dataTransfer.items.add(new File([''], 'test-file.pdf'))

    const inputDebugEl  = fixture.debugElement.query(By.css('input[type=file]'));
    inputDebugEl.nativeElement.files = dataTransfer.files;

    inputDebugEl.nativeElement.dispatchEvent(new InputEvent('change'));

    fixture.detectChanges();

    expect(component.uploadedFile).toBeTruthy()
    expect(component.uploadedFile).toBe('test-file.pdf')
    
});

it('file change event should arrive in handler', () => {
    const element = fixture.nativeElement;
    const input = element.querySelector('#file');
    spyOn(component, 'onFileSelected');
    input.dispatchEvent(new Event('change'));
    fixture.detectChanges();
    expect(component.onFileSelected).toHaveBeenCalled();
});
票数 10
EN

Stack Overflow用户

发布于 2019-04-16 10:01:40

对于上述部分的100%代码覆盖率,我添加了以下两个测试用例。这对我有用。

代码语言:javascript
复制
it('should upload the file - checkFileExist = true', () => {
    spyOn(component, 'checkFileExist').and.returnValue(true);
    spyOn(postalService,'importPostalCodes').and.callThrough();
    component.importFile();
    expect(postalService.importPostalCodes).toHaveBeenCalled();
});

it('should upload the file - checkFileExist = false', () => {
    spyOn(component, 'checkFileExist').and.returnValue(false);
    spyOn(postalService,'importPostalCodes').and.callThrough();
    component.importFile();
    expect(postalService.importPostalCodes).toHaveBeenCalledTimes(0);
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55356093

复制
相关文章

相似问题

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