Tengo un emisor de eventos @Output en mi componente y para probar el valor emitido por él he hecho algo como esto:
component.uploadFinished = {emit: jasmine.createSpy()}; --- --- expect(component.uploadFinished.emit).toHaveBeenCalledWith({response: jasmine.any(HttpResponse)})Aquí no me permite escribir component.uploadFinished ya que dice que es una propiedad de solo lectura. Cualquier ayuda será apreciada. También el componente aquí es de tipo TestComponent
EDITAR 1:
este es mi archivo ts y la función para la que estoy escribiendo las pruebas
async fileUpload() { this.fileUploadStatus = 'uploading'; const file = this.uploadFile[0]; const formData = new FormData(); formData.append(this.uploadConfig.fieldName, file, file.name); const req = new HttpRequest(this.uploadConfig.method, this.uploadConfig.url, formData, { headers: this.uploadConfig.headers }); try { const response = await this.http.request(req).pipe( retry(3) ).toPromise() as HttpResponse<any>; this.fileUploadStatus = 'success'; this.uploadFinished.emit({response}); } catch (error) { this.uploadFinished.emit({error}); } }Y esta es la prueba unitaria.
it('should emit success response', async () => { component.uploadFinished = {emit: jasmine.createSpy()}; // eslint-disable-next-line max-len component.uploadConfig = { method: 'POST', url: '/api/attachments', fieldName: 'file', // eslint-disable-next-line @typescript-eslint/naming-convention headers: new HttpHeaders({ 'Accept': 'application/json' }) }; component.handleFiles(createFileList(['matching.fmwr'])); fixture.detectChanges(); component.fileUpload(); // trigger upload // mock request const attachment = { id: 201, fileName: 'matching.fmwr' }; const req = httpMock.expectOne('/api/attachments'); req.flush(attachment); httpMock.verify(); // api call is async function and there is time delay in emit await (new Promise((resolve, reject) => { setTimeout(()=>{ expect(component.uploadFinished.emit).toHaveBeenCalledWith({response: jasmine.any(HttpResponse)}) return resolve(true); }, 1000); })) });Tengo que usar setTimeout ya que debido a la emisión de la función asíncrona no se llamaba según era necesario. Apreciaría si se puede sugerir una mejor manera para esto.
Puede deshabilitar la verificación de TypeScript para una línea de código:
// @ts-ignore expect(component.uploadFinished.emit).toHaveBeenCalledWith({response)Nota: le sugiero que solo use esto en archivos de especificaciones. En general es un último recurso.
Solucioné este problema cambiando
component.uploadFinished = {emit: jasmine.createSpy()};para
spyOn(component.uploadFinished, 'emit');