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

问题描述 投票:0回答:1

我正在尝试在角度7中编写文件上传方法的单元测试。在测试窗口中获取以下错误。我是角度单元测试的新手。有人可以帮忙,如何添加模拟文件以获得完整的代码覆盖率?

TypeError:无法设置undefined的属性“value”

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

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

组件中的方法

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,

<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%的代码覆盖率。

Code coverage image

angular karma-jasmine angular-test angular-testing
1个回答
0
投票

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

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.