Testarea codului asincron
Se întâmplă frecvent în JavaScript să se execute cod asincron. Atunci când aveţi cod care se execută în mod asincron, Jest trebuie să ştie când codul pe care-l testează s-a completat de executat, înainte de a trece la un alt test. Jest are mai multe moduri pentru a rezolva acest lucru.
Promisiuni
Return a promise from your test, and Jest will wait for that promise to resolve. If the promise is rejected, the test will fail.
For example, let's say that fetchData
returns a promise that is supposed to resolve to the string 'peanut butter'
. We could test it with:
test('the data is peanut butter', () => {
return fetchData().then(data => {
expect(data).toBe('peanut butter');
});
});