Как написать модульное тестирование для метода загрузки файлов в Angular 7 (или 2+) - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь написать модульное тестирование для метода загрузки файла в angular 7. Получение приведенной ниже ошибки в окне тестирования. Я новичок в угловых юнит-тестах. Может ли кто-нибудь помочь, Как добавить макетные файлы, чтобы получить полное покрытие кода?

TypeError: Невозможно установить свойство 'value' из неопределенного

Вот мой код модульного теста (файл спецификации),

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% покрытие кода.

Код покрытия изображения

1 Ответ

0 голосов
/ 16 апреля 2019

Для 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);
});
...