我正在使用Jasmine&Karma进行角度应用程序的单元测试。我写了这样的单元测试:
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();}
)
}));
})
再一次,Jasmine告诉我spec has no expectations
等待订阅没有做任何事......
await service.getAll(...).subscribe(...)
您需要将observable转换为Promise。另外,确保你的observable完成,否则你只需要获得第一个元素,或者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');
}
}));
})