Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

175
Vistas
Not able to use the read-only property of a component in jasmine unit tests

I have an @Output event Emitter in my component and in order to test the value emitted by it I have done something like this:

component.uploadFinished = {emit: jasmine.createSpy()};
---
---
expect(component.uploadFinished.emit).toHaveBeenCalledWith({response: jasmine.any(HttpResponse)})

Here it is not allowing me to write component.uploadFinished as it says that its a read-only property. Any help will be appreciated. Also component here is of type TestComponent

EDIT 1:

this is my ts file and the function for which I am writing the tests

  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});
    }
  }

And this is unit test

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);
    }))
  });

I have to use setTimeout since due to async function emit was not getting called as needed. Would appreciate if a better way for this can be suggested.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You can disable TypeScript checking for a line of code:

// @ts-ignore
expect(component.uploadFinished.emit).toHaveBeenCalledWith({response)

Note: I would suggest you only use this in spec files. In general it's a last resort

over 4 years ago · Santiago Trujillo Denunciar

0

I fixed this issue by changing

component.uploadFinished = {emit: jasmine.createSpy()};

to

spyOn(component.uploadFinished, 'emit');
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda