Error in Angular asynchronous test with Jest
I want to test a service with jest, but I'm having trouble testing an asynchronous function that gives a get in my api.
The error I get is as follows:
FAIL tests/documentos.service.spec.ts (11.205 s)
DocumentosService
× encountered a declaration exception (518 ms)
● DocumentosService › encountered a declaration exception
Cannot call Promise.then from within a sync test.
Function in service:
async listarDocumentos():Promise<Documento[]>{
let documentos: Documento[];
await this.http.get<Documento[]>(`${urlDocumentos}`, {observe:'body'}).toPromise()
.then(res =>{
if(res.length <= 0) throw 'Não existem documentos cadastrados'
documentos = res
})
.catch((error:HttpErrorResponse) =>{
this.mensagem.error(`Erro ao listar documentos: ${error.message}`,`Erro: ${error.status || 'Listar Documentos'}`)
})
return documentos
}
Test file:
import { TestBed, ComponentFixture } from '@angular/core/testing';
import { DocumentosService } from '../src/app/service/documentos/documentos.service';
import { DocumentosDoSistemaComponent } from '../src/app/documentos-do-sistema/documentos-do-sistema.component';
import { Documento } from '../src/app/service/documentos/documentos.model';
let componenteFake: DocumentosDoSistemaComponent;
let fixture: ComponentFixture<DocumentosDoSistemaComponent>;
let documentosService: DocumentosService;
describe('DocumentosService', () => {
beforeEach(() => TestBed.configureTestingModule({
declarations:[DocumentosDoSistemaComponent],
providers:[DocumentosService]
}));
fixture = TestBed.createComponent(DocumentosDoSistemaComponent);
componenteFake = fixture.componentInstance;
documentosService = TestBed.get(DocumentosService);
test('Teste do service de documentos', async () =>{
let documentos:Documento[];
documentos = await documentosService.listarDocumentos();
expect(documentos.length).toBeGreaterThan(0);
})
});
0
Author: Danilo Silva Fernandes, 2020-07-15