Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

258
Views
¿Cómo se pueden probar los métodos de clase simulada dentro de la clase?

Tengo una clase simulada para un servicio web:

src/_ se burla de _/ExternalService.ts

 export default class ExternalService { async queryService(skus: string): Promise<any> { try { return await this.mockResponse; } catch (error) { return error; } } mockResponse: any = { data: { recordSetCount: 6, isMock: true, items: [ // Mock items ] } };

Este método llama correctamente a la clase simulada en Jest:

src/Accesorios.ts

 async getAccesoriesFromService(skus: string): Promise<any> { const externalService = new ExternalService(); const productsData = []; try { const products = await externalService.queryService(skus); if (!products.data?.items?.length) { return { errorCode: -4 }; } ... return { errorCode: 0, products: productsData }; } catch (error) { return { errorCode: -1, error }; } }

En esta prueba, quiero anular el simulacro con otro simulacro:

_ pruebas__/main.spec.ts

 const accesories = new Accesories(); const externalService = new ExternalService(); jest.mock('../src/ExternalService'); it('get no accesories from service', async () => { const mockResponseNoRecords: any = { data: { recordSetCount: 0, items: [] // empty array } }; jest.spyOn(externalService, 'queryService').mockImplementation((): any => { return mockResponseNoRecords; }); try { await accesories.getAccesoriesFromService('string with skus'); } catch (error) { expect(error.errorCode).toBe(-4); } }

Pero cuando ejecuto la prueba, obtengo estos resultados de console.log:

 console.log products in test code: { mockResponseNoRecords: { data: { recordSetCount: 0, items: [] } } at __tests__/main.spec.ts:96:11 console.log products in actual code: { data: { recordSetCount: 6, isMock: true, items: [ // Items from the mock class ] } }

Y la prueba pasa porque se llamó al simulacro original, no se espió con éxito

Lo que quiero lograr es anular el método en la clase simulada para que falle, pero se está llamando al simulacro original.

about 4 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!