规格没有期望Angular 7

时间:2019-02-28 06:46:32

标签: angular unit-testing jasmine karma-jasmine

我正在使用Jasmine&Karma进行Angle app的单元测试。我已经写过这样的单元测试:

describe('#getAll', async () => {
    it('#should return user intergration_tester', inject([UsersService], async(service: UsersService) => {
        await service.getAll('integration_tester', access_token).subscribe(
            user => {
                expect(user[0].firstName).toContain('Integration');
                done();
            })
      }));

      it('#should return error 404', inject([UsersService], (service: UsersService) => {
        service.getAll('integration_tester', '').subscribe(
            user => {expect(user[0].firstName).not.toContain('Integration');},
            err => { expect(err).toContain('error');}
        )
      }));
})

当我执行测试用例时,我看到一条消息SPEC HAS NO EXPECTATIONS对于这两个测试用例。我想知道为什么它显示规范没有期望。

然后,我遵循了本文中建议的解决方案:Spec has no expectations - Jasmine testing the callback function

使用done()

describe('#getAll', async () => {
    it('#should return user intergration_tester', inject([UsersService], async(service: UsersService, done) => {
        await service.getAll('integration_tester', access_token).subscribe(
            user => {
                expect(user[0].firstName).toContain('Integration');
                done();
            })
      }));

      it('#should return error 404', inject([UsersService], (service: UsersService, done) => {
        service.getAll('integration_tester', '').subscribe(
            user => {expect(user[0].firstName).not.toContain('Integration'); done();},
            err => { expect(err).toContain('error'); done();}
        )
      }));
})

再次,茉莉花告诉我spec has no expectations

1 个答案:

答案 0 :(得分:0)

等待订阅没有任何作用...

await service.getAll(...).subscribe(...)

您需要将可观察对象转换为Promise。另外,请确保您的可观察性完成,否则您只需要获取第一个元素,否则promise将永远无法解决(假设getAll继续发送事件或其他内容-但您应该在测试运行期间超时)。这应该可以解决问题:

describe('#getAll', async () => {
    it('#should return user intergration_tester', inject([UsersService], async (service: UsersService) => {
        const user = await service.getAll('integration_tester', access_token).toPromise();
        expect(user[0].firstName).toContain('Integration');
    }));

    it('#should return error 404', inject([UsersService], async (service: UsersService) => {
        try {
            const user = await service.getAll('integration_tester', '').toPromise();

            expect(user[0].firstName).not.toContain('Integration');
        } catch (err) {
            // why do you also expect an error to be thrown?
            expect(err).toContain('error');
        }
    }));
})