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

16

这是一个有趣的问题:我正在尝试测试一个使用Ionic BarcodeScanner的服务。为了进行测试,我基于ionic单元测试库创建了一个存储库。我通过spyOn(..).and.callFake(..)模拟BarcodeScanner.scan方法。

问题在于:当我从组件调用scan方法时它能正常工作,但当我在服务中执行完全相同的操作时,它会抛出超时错误。

组件测试代码:

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

服务测试代码:

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

以这种方式测试Angular 2服务是否存在已知问题? 感谢任何帮助!

1个回答

6
问题是不调用inject函数。
现在服务的测试代码如下所示:
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!!
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接