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

307
Views
Jest no detecta mi llamada simulada en el bloque .catch de promesa

Jest no parece estar detectando mis llamadas simuladas en el bloque catch. Sin embargo, si no me burlo del método handleError , recibiré un error. He intentado varias formas de hacer la promesa rechazada devuelta, pero hasta ahora no he tenido suerte.

Probé las devoluciones de llamada, Promise.reject, Promise((res, rej) => {})

Código que se está probando:

 module.exports = class PresetDropdown { constructor (Api, objectId, titleSort) { this.Api = Api; this.objectId; = objectId; this.presets = []; } handleError (err) { console.log(err) // more functionality } get () { this.Api.getMany(this.objectId) .then((data) => { this.handleEmpty(data); this.isError = false; }) .catch((err) => { this.isError = true; this.handleError(err); }); } };

Prueba (broma):

 test('Expect call from handleError after reject promise', async () => { // assemble // return the class const Module = getModule(); const mockRejectedPromise = jest.fn(() => { return Promise.reject(Error(mockError)); }); mockApi.getMany = mockRejectedPromise; const module = new Module(mockApi, '1', null); const mockHandleError = jest.fn(() => {}); PresetTemplate.handleError = mockHandleError; // act await PresetTemplate.get(mockScope); // assert expect(mockHandleError).toHaveBeenCalledTimes(1); // DOES NOT DETECT CALL // Test CASE FAILS HERE ^ });
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Dado que la clase PresetDropdown acepta un objeto Api , puede crear un objeto Api y pasarlo a la clase. Luego simule el valor resuelto/rechazado para el método Api.getMany() , para que pueda probar diferentes ramas de código.

P.ej

presetDropdown.js :

 module.exports = class PresetDropdown { constructor(Api, objectId, titleSort) { this.Api = Api; this.objectId = objectId; this.presets = []; } handleError(err) { console.log(err); } handleEmpty(data) { console.log(data); } get() { return this.Api.getMany(this.objectId) .then((data) => { this.handleEmpty(data); this.isError = false; }) .catch((err) => { this.isError = true; this.handleError(err); }); } };

presetDropdown.test.js :

 const PresetDropdown = require('./presetDropdown'); describe('71164955', () => { test('should handle data', async () => { const mockApi = { getMany: jest.fn().mockResolvedValueOnce('fake data'), }; const instance = new PresetDropdown(mockApi, '1'); await instance.get(); expect(instance.isError).toBeFalsy(); }); test('should handle error', async () => { const mockError = new Error('fake error'); const mockApi = { getMany: jest.fn().mockRejectedValueOnce(mockError), }; const instance = new PresetDropdown(mockApi, '1'); await instance.get(); expect(instance.isError).toBeTruthy(); }); });

Resultado de la prueba:

 PASS stackoverflow/71164955/presetDropdown.test.js 71164955 ✓ should handle data (14 ms) ✓ should handle error (3 ms) console.log fake data at PresetDropdown.handleEmpty (stackoverflow/71164955/presetDropdown.js:11:13) console.log Error: fake error at Object.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71164955/presetDropdown.test.js:12:23) at Object.asyncJestTest (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:106:37) at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:45:12 at new Promise (<anonymous>) at mapper (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:28:19) at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:75:41 at processTicksAndRejections (internal/process/task_queues.js:93:5) at PresetDropdown.handleError (stackoverflow/71164955/presetDropdown.js:8:13) Test Suites: 1 passed, 1 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 1.311 s
about 4 years ago · Juan Pablo Isaza Report
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!