角度异步单元测试过早完成

时间:2018-01-04 03:28:01

标签: angular unit-testing typescript jasmine karma-jasmine

以下针对Angular的单元测试(使用Jasmine-Karma)过早完成而未进行测试结束。请帮忙。

输出:

LOG: '{"a":"b"}'
LOG: '1'
LOG: 'Finished!'

错误:

null: Unhandled Promise rejection: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out ; Zone: ProxyZone ; Task: Promise.then ; Value:
null: Error: 'expect' was used when there was no current spec, this could be because an asynchronous test timed out

单元测试:

import 'rxjs/add/observable/of';

import { } from 'jasmine';
import { TestBed, inject } from '@angular/core/testing';
import { async } from '@angular/core/testing';
import { Observable } from 'rxjs/Observable';

interface FileResponse {
    data: Blob;
}

class BlobUtil {
    public static asString(blob: Blob) {
        return new Promise<string>((resolve, reject) => {
            var reader = new FileReader();
            reader.onload = (event: any) => resolve(event.target.result);
            try {
                reader.readAsText(blob);
            }
            catch (e) {
                reject(e);
            }
        });
    }
}

class Service {
    public static async SafeCall(executor: Observable<FileResponse>,
        success: (response: string) => void, failure: (error: string) => void) {
        try {
            var response = await executor.toPromise();
            success(await this.Handle(response));
        }
        catch (e) {
            failure(e.message);
        }
    }

    private static async Handle(response: FileResponse) {
        return await BlobUtil.asString(response.data);
    }
}

describe('Tests', () => {

    afterEach(() => {
        console.log("Finished!");
    });

    it("test", async(inject([],
        async () => {
            var request = Observable.of({ data: new Blob(['{"a":"b"}'], { type: 'text/plain' }) });
            await Service.SafeCall(request, response => console.log(response), error => console.log(error));
            expect(true).toBeTruthy();
            console.log("1");
            await Service.SafeCall(request, response => console.log(response), error => console.log(error));
            console.log("2");
            expect(true).toBeTruthy();
            console.log("3");
            await Service.SafeCall(request, response => console.log(response), error => console.log(error));
            console.log("4");
            expect(true).toBeTruthy();
            console.log("5");
        })));
    });

1 个答案:

答案 0 :(得分:1)

看起来这是Angular的默认单元测试框架Jasmine的一个基本问题(时间来看看你的单元测试覆盖范围内的人 - 这对于在发布版本中失败来说太基础了)。我找到了一个解决方法,直到他们能够正确修复它。

使用以下内容替换async函数,它将按预期工作。

export function async(specFunc) {
  return (done) => {
      specFunc().then(() => {
          done();
      }).catch((error) => {
          done.fail(error);
      });
  };
}

// it("test", async(inject([], ...

P.S。我无法在Jasmine的GitHub回购中找到任何单元测试...请告诉我那里的单元测试!

相关问题