在Angular 2服务中测试异步(Promise)方法

Sen*_*nza 16 angular-services angular2-services ionic3 angular

这是一个有趣的问题:我正在尝试测试使用Ionic BarcodeScanner的服务.我有一个基于离子单元测试库的repo ,以便尝试测试.我正在嘲笑BarcodeScanner.scan方法spyOn(..).and.callFake(..)

问题:当我从组件调用扫描方法时,它可以工作.当我在服务中执行完全相同的操作时,它会抛出超时.

组件测试代码:

it("should be able to set a spy on the scanner and test the component", done => {
    const testBC = "123456";
    const spy = spyOn(TestBed.get(BarcodeScanner), "scan");
    spy.and.callFake(() => {
        return new Promise((resolve, reject) => {
            resolve(testBC);
        })
    });

        component.testScanner().then(res => {
            expect(res).toBe(testBC);
            done();
        }, reason => {
            expect(true).toBe(false);
            done();
        })
});
Run Code Online (Sandbox Code Playgroud)

服务测试代码:

it("should be able to set a spy on the scanner and test the service", done => {
    const testBC = "123456";
    const spy = spyOn(TestBed.get(BarcodeScanner), "scan");
    spy.and.callFake(() => {
        return new Promise((resolve, reject) => {
            resolve(testBC);
        })
    });

    inject([TestService], (service) => {
        service.testScanner().then(res => {
            expect(res).not.toBe(testBC);
            done()
        }, reason => {
            expect(true).toBe(false);
            done();
        })
    })
});
Run Code Online (Sandbox Code Playgroud)

是否有任何已知的Angular 2测试服务问题?任何帮助赞赏!

Sen*_*nza 6

问题是没有调用注入函数.

该服务的测试代码现在看起来像这样:

it("should be able to set a spy on the scanner and test the service", done => {
    const testBC = "123456";
    const spy = spyOn(TestBed.get(BarcodeScanner), "scan");
    spy.and.callFake(() => {
        return new Promise((resolve, reject) => {
            resolve(testBC);
        })
    });

    inject([TestService], (service) => {
        service.testScanner().then(res => {
            expect(res).not.toBe(testBC);
            done()
        }, reason => {
            expect(true).toBe(false);
            done(); 
        })
    })(); //<-- do not forget these braces!!
});
Run Code Online (Sandbox Code Playgroud)