如何用Angular和Jest在服务中测试http请求函数



我创建了一个返回json对象的简单服务。


getCountries() {
return this.httpService.get('../../assets/countries.json');
}

测试

describe('TestServiceService', () => {
let service: TestServiceService;
let httpController: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule]
});
httpController = TestBed.inject(HttpTestingController);
service = TestBed.inject(TestServiceService);
});
it('return countries', () => {
service.getCountries().subscribe(resp => {
expect(resp).toEqual({'test': 0});
});
const req = httpController.expectOne({
method: 'GET',
url: '../../assets/countries.json'
});
req.flush({'test': 1});
httpController.verify();
});
});

当我尝试测试它时,它使用Jasmine工作得很好,但是在将Jest设置为测试运行器后,测试总是通过为ok,尽管它们不ok。当我用Jest Runner插件在VS Code中调试测试时,它检测到错误,但以正常方式运行测试时,它通过为ok。

更新:

使用回调'完成'作为temp_user建议我得到一个超时错误。我可以设置一个更长的超时,比如20秒或更长时间。但我不知道,我觉得对于这么简单的测试来说这有点过分了,对吧?

thrown: "Exceeded timeout of 5000 ms for a test.
Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
19 |   });
20 |
> 21 |   it('return countries', (done) => {
|   ^
22 |     service.getCountries().subscribe(resp => {
23 |       expect(resp).toEqual({'test': 0});
24 |       done();

有什么建议吗?还有其他合适的方法吗?谢谢你

你可以将可观察对象转换为promise,并应用fakeAsync/tick来完成待处理的任务

it('return countries', fakeAsync(() => {
...
service.getCountries().subscribe.toPromise().then(resp => {
...
})
...
req.flush({'test': 1});
httpController.verify();
tick();

这是因为您正在运行异步代码,而Jasmine并不能开箱即用。

it('return countries', (done) => { // Add a callback here
service.getCountries().subscribe(resp => {
expect(resp).toEqual({'test': 0});
done(); // Call the callback here
});
const req = httpController.expectOne({
method: 'GET',
url: '../../assets/countries.json'
});
req.flush({'test': 1});
httpController.verify();
});

最新更新