包含FileReader.onload的角度单元测试不适用于async / whenStable或fakeAsync / tick

时间:2019-02-10 00:43:53

标签: javascript angular jasmine karma-jasmine filereader

我正在为我的angular 7应用程序添加一些单元测试,但是由于使用async / whenStable,fakeAsync和promises不能按预期工作,因此我不确定如何处理与FileReader的交互。

  • 我正在测试的行为:文件上传后,我需要验证服务documentService.sendDocument是否被调用。

第一种方法

在发现测试FileReader.onload的问题之前,我只是尝试了在没有异步的情况下对其进行测试。

控制器代码

onFileGovernmentIdChange(event) {
    console.log('::: Init onFileGovernmentIdChange');
    const updateFunction = () => {
        console.log('::: BEFORE update fileGovernmentIdUploaded - ', this.fileGovernmentIdUploaded);
        this.fileGovernmentIdUploaded = true;
        console.log('::: AFTER update fileGovernmentIdUploaded - ', this.fileGovernmentIdUploaded);
    }
    this.saveFileFromInputSimple(event, DOCUMENT_TYPE.STORE_GOVERNMENT_ID, updateFunction);
    console.log('::: End onFileGovernmentIdChange');
}

private saveFileFromInputSimple(event, documentType: DOCUMENT_TYPE, updateState: () => any) {
    console.log('::: Init saveFileFromInputSimple');
    const reader = new FileReader();

    if (event.target.files && event.target.files.length > 0) {
        console.log('::: Event with files...');
        const file = event.target.files[0];
        reader.onload = () => {
            this.documentService
                .sendDocument(file.name, file.type, reader.result.toString(), documentType)
                .subscribe(
                    response => {
                        console.log('::: sendDocument - Subscribe OK');
                        updateState()
                    },
                    error => {
                        console.log('::: sendDocument - Subscribe ERROR');
                        this.showDefaultErrorDialog()
                    }
                );
        };
        console.log('::: Onload callback assigned...');
        reader.readAsDataURL(file);
    }
    console.log('::: End saveFileFromInputSimple');
}


UnitTest规范代码

fit('simple testing', () => {
    const documentService = TestBed.get(DocumentsService);
    const catalogService: CatalogService = TestBed.get(CatalogService);
    const customEvent = {
        target: {
            files: [new Blob(['ssdfsdgdjghdslkjghdjg'], { type: 'pdf' })]
        }
    };

    const commerceResponse = new CommerceResponse();
    commerceResponse.commissionPercentage = '11';

    spyOn(catalogService, 'getCatalog').and.returnValue(of({ catalogs: [] }));
    spyOn(documentService, 'getCommerceInfo').and.returnValue(of(commerceResponse));
    spyOn(documentService, 'sendDocument').and.returnValue(of({ response: 'ok' }));

    fixture.detectChanges();//Apply onInit changes
    console.log('::: Before calling onFileGovernmentIdChange()');
    component.onFileGovernmentIdChange(customEvent);
    console.log('::: After calling onFileGovernmentIdChange()');
    console.log('::: Before expects... ');
    expect(component.fileGovernmentIdUploaded).toBeTruthy();
    // expect(documentService.sendDocument).toHaveBeenCalledTimes(1);
    console.log('::: After expects... ');
});

UnitTest结果

LOG: '::: Before calling onFileGovernmentIdChange()'
LOG: '::: Init onFileGovernmentIdChange'
LOG: '::: Init saveFileFromInputSimple'
LOG: '::: Event with files...'
LOG: '::: Onload callback assigned...'
LOG: '::: End saveFileFromInputSimple'
LOG: '::: End onFileGovernmentIdChange'
LOG: '::: After calling onFileGovernmentIdChange()'
LOG: '::: Before expects... '
LOG: '::: After expects... '
Chrome 71.0.3578 (Mac OS X 10.13.6) DocumentsComponent simple testing FAILED
        Expected undefined to be truthy.
            at UserContext.<anonymous> src/app/documents/documents.component.spec.ts:146:52)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)

UnitTest分析

onload方法中的代码永远不会执行

第二种方法

在没有观察者的情况下测试FileReader.onload:为了遵循工作流程,我在onload内移除了观察者,以验证是否可能是问题所在。

控制器代码

private saveFileFromInputSimple(event, documentType: DOCUMENT_TYPE, updateState: () => any) {
    console.log('::: Init saveFileFromInputSimple');
    const reader = new FileReader();

    if (event.target.files && event.target.files.length > 0) {
        console.log('::: Event with files...');
        const file = event.target.files[0];
        reader.onload = () => {
            console.log('::: ONLOAD executed');
        };
        console.log('::: Onload callback assigned...');
        reader.readAsDataURL(file);
    }
    console.log('::: End saveFileFromInputSimple');
}

UnitTest规范代码

与第一种方法相同

UnitTest结果

LOG: '::: Before calling onFileGovernmentIdChange()'
LOG: '::: Init onFileGovernmentIdChange'
LOG: '::: Init saveFileFromInputSimple'
LOG: '::: Event with files...'
LOG: '::: Onload callback assigned...'
LOG: '::: End saveFileFromInputSimple'
LOG: '::: End onFileGovernmentIdChange'
LOG: '::: After calling onFileGovernmentIdChange()'
LOG: '::: Before expects... '
LOG: '::: After expects... '
Chrome 71.0.3578 (Mac OS X 10.13.6) DocumentsComponent simple testing FAILED
        Expected undefined to be truthy.
            at UserContext.<anonymous> src/app/documents/documents.component.spec.ts:146:52)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:387:1)
Chrome 71.0.3578 (Mac OS X 10.13.6): Executed 1 of 46 (1 FAILED) (0 secs / 0.314 secs)
Chrome 71.0.3578 (Mac OS X 10.13.6) DocumentsComponent simple testing FAILED
        Expected undefined to be truthy.
            at UserContext.<anonymous> src/app/documents/documents.component.spec.ts:146:52)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
LOG: '::: ONLOAD executed'

UnitTest分析

现在onload方法中的代码已执行,但由于它是在末尾执行的,因此看起来像是一个异步操作。

第三种方法

使用异步单元测试测试FileReader.onload:当我发现某种异步操作时,我加入了async/fixture.whenStable角度组合以等待异步代码完成。

控制器代码

与第二种方法一样

UnitTest规范代码

fit('Testing with async/fixture.whenStable', async(() => {
    const documentService = TestBed.get(DocumentsService);
    const catalogService: CatalogService = TestBed.get(CatalogService);
    const customEvent = {
        target: {
            files: [new Blob(['ssdfsdgdjghdslkjghdjg'], { type: 'pdf' })]
        }
    };

    const commerceResponse = new CommerceResponse();
    commerceResponse.commissionPercentage = '11';

    spyOn(catalogService, 'getCatalog').and.returnValue(of({ catalogs: [] }));
    spyOn(documentService, 'getCommerceInfo').and.returnValue(of(commerceResponse));
    spyOn(documentService, 'sendDocument').and.returnValue(of({ response: 'ok' }));

    fixture.detectChanges();//Apply onInit changes
    console.log('::: Before calling onFileGovernmentIdChange()');
    component.onFileGovernmentIdChange(customEvent);
    console.log('::: After calling onFileGovernmentIdChange()');
    console.log('::: Before expects... ');

    fixture.whenStable().then(() => {
        fixture.detectChanges();
        console.log('::: whenStable Init');
        expect(component.fileGovernmentIdUploaded).toBeTruthy();
        // expect(documentService.sendDocument).toHaveBeenCalledTimes(1);
        console.log('::: whenStable End');
    });

    console.log('::: After expects... ');
}));

UnitTest结果

LOG: '::: Before calling onFileGovernmentIdChange()'
LOG: '::: Init onFileGovernmentIdChange'
LOG: '::: Init saveFileFromInputSimple'
LOG: '::: Event with files...'
LOG: '::: Onload callback assigned...'
LOG: '::: End saveFileFromInputSimple'
LOG: '::: End onFileGovernmentIdChange'
LOG: '::: After calling onFileGovernmentIdChange()'
LOG: '::: Before expects... '
LOG: '::: After expects... '
LOG: '::: whenStable Init'
LOG: '::: whenStable End'
**LOG: '::: ONLOAD executed'**

UnitTest分析

正如预期的那样,该方法完成后将执行whenStable代码,但是onload方法将在最后继续执行。 谷歌搜索,我发现将onload部分包装在Promise中以确保它可以被Angular异步跟踪更好。

第四种方法

在承诺中包装onload,并验证其是否与async/whenStable结构兼容。

控制器代码

private readFileAsync(file): Promise<string> {
    console.log('::: readFileAsync Init');
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => {
            console.log(':::: Promise Resolved in ONLOAD')
            resolve(reader.result.toString());
        }
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

private saveFileFromInputWithPromise(event, documentType: DOCUMENT_TYPE, updateState: () => any) {
    console.log('::: Init saveFileFromInputWithPromise');

    if (event.target.files && event.target.files.length > 0) {
        console.log('::: Event with files...');
        const file = event.target.files[0];

        this.readFileAsync(file)
            .then(fileContent => {
                console.log('::: File with content', fileContent);
                updateState();
            }).catch(error => console.log('::: File load error', error));
    }
    console.log('::: End saveFileFromInputWithPromise');
}

UnitTest规范代码

与第三种方法相同

UnitTest结果

LOG: '::: Before calling onFileGovernmentIdChange()'
LOG: '::: Init onFileGovernmentIdChange'
LOG: '::: Init saveFileFromInputWithPromise'
LOG: '::: Event with files...'
LOG: '::: readFileAsync Init'
LOG: '::: End saveFileFromInputWithPromise'
LOG: '::: End onFileGovernmentIdChange'
LOG: '::: After calling onFileGovernmentIdChange()'
LOG: '::: Before expects... '
LOG: '::: After expects... '
LOG: '::: whenStable Init'
LOG: '::: whenStable End'
LOG: ':::: Promise Resolved in ONLOAD'
LOG: '::: File with content', 'data:pdf;base64,c3NkZnNkZ2RqZ2hkc2xramdoZGpn'
LOG: '::: BEFORE update fileGovernmentIdUploaded - ', undefined
LOG: '::: AFTER update fileGovernmentIdUploaded - ', true
Chrome 71.0.3578 (Mac OS X 10.13.6) DocumentsComponent Testing with async/fixture.whenStable FAILED
        Expected undefined to be truthy.
            at http://localhost:9877/_karma_webpack_/webpack:/src/app/documents/documents.component.spec.ts:176:56
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at AsyncTestZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.AsyncTestZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:713:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:285:1)

UnitTest分析

whenStable函数之后再次解决承诺。

第五种方法

由于async/whenStable不能按预期工作,因此我尝试更改为fakeAsync/tick/flush结构。

控制器代码

与第四种方法相同(在承诺中包括onload

UnitTest规范代码

fit('Testing with fakeAsync/tick/flush', fakeAsync(() => {
    const documentService = TestBed.get(DocumentsService);
    const catalogService: CatalogService = TestBed.get(CatalogService);
    const customEvent = {
        target: {
            files: [new Blob(['ssdfsdgdjghdslkjghdjg'], { type: 'pdf' })]
        }
    };

    const commerceResponse = new CommerceResponse();
    commerceResponse.commissionPercentage = '11';

    spyOn(catalogService, 'getCatalog').and.returnValue(of({ catalogs: [] }));
    spyOn(documentService, 'getCommerceInfo').and.returnValue(of(commerceResponse));
    spyOn(documentService, 'sendDocument').and.returnValue(of({ response: 'ok' }));

    fixture.detectChanges();
    console.log('::: Before calling onFileGovernmentIdChange()');
    component.onFileGovernmentIdChange(customEvent);
    console.log('::: After calling onFileGovernmentIdChange()');
    console.log('::: Before expects... ');

    fixture.detectChanges();
    tick();
    flushMicrotasks();
    flush();
    console.log('::: After Flush Init');
    expect(component.fileGovernmentIdUploaded).toBeTruthy();
    // expect(documentService.sendDocument).toHaveBeenCalledTimes(1);
    console.log('::: After Flush End');
    console.log('::: After expects... ');
}));

UnitTest结果

LOG: '::: Before calling onFileGovernmentIdChange()
LOG: '::: Init onFileGovernmentIdChange'
LOG: '::: Init saveFileFromInputWithPromise'
LOG: '::: Event with files...'
LOG: '::: readFileAsync Init'
LOG: '::: End saveFileFromInputWithPromise'
LOG: '::: End onFileGovernmentIdChange'
LOG: '::: After calling onFileGovernmentIdChange()'
LOG: '::: Before expects... '
LOG: '::: After Flush Init'
LOG: '::: After Flush End'
LOG: '::: After expects... '
Chrome 71.0.3578 (Mac OS X 10.13.6) DocumentsComponent Testing with async/fixture.whenStable FAILED
        Expected undefined to be truthy.
            at UserContext.<anonymous> src/app/documents/documents.component.spec.ts:211:52)
            at UserContext.<anonymous> node_modules/zone.js/dist/zone-testing.js:1424:1)
            at ZoneDelegate../node_modules/zone.js/dist/zone.js.ZoneDelegate.invoke node_modules/zone.js/dist/zone.js:388:1)
            at ProxyZoneSpec.push../node_modules/zone.js/dist/zone-testing.js.ProxyZoneSpec.onInvoke node_modules/zone.js/dist/zone-testing.js:288:1)
LOG: ':::: Promise Resolved in ONLOAD'
LOG: '::: File with content', 'data:pdf;base64,c3NkZnNkZ2RqZ2hkc2xramdoZGpn'
LOG: '::: BEFORE update fileGovernmentIdUploaded - ', undefined
LOG: '::: AFTER update fileGovernmentIdUploaded - ', true

UnitTest分析

同样,Profise是在fakeAsync / tick / flushMicrotasks / flush结构之后解决的

怎么了?

我遵循了我发现的每个教程以及尝试将FileReader.onload包含在测试中的每种方法(因为该方法调用了我要监视和验证的服务),但是方法总是在由提供的异步块之后解析。有角度的。我看到了模拟window.fileReader的其他方法,但这不是测试的目的。

那么有人能告诉我我的代码或测试方式出了什么问题吗?

1 个答案:

答案 0 :(得分:1)

很棒的帖子,完美地描述了我的夜晚。

fakeAsync不支持FileReader似乎是一个已知问题,因为“从根本上来说,它不是与计时器相关的异步操作”。

请参阅:https://github.com/angular/zone.js/issues/1120