export const waitFor = async cb => { let c = 0 async function f () { console.log('inside f') try { return await cb() } catch (error) { if (c < 10) { c += 1 setTimeout(f, 500) } } } const result = await f() return result } Tengo esta utilidad para esperar mi devolución de llamada y volver a intentarlo 10 veces con un retraso de 500ms , y quiero agregar una prueba para la waitFor .
describe('testUtilis', () => { it('should wait till callback resolves', async () => { const cb = async () => { await sleep(500) return 'Hello' } const result = await waitFor(cb) expect(result).toBe('Hello') }) it('should retry a failed callback', async () => { const globalNow = Date.now() const getByText = async () => { const now = Date.now() const gapInMilliseconds = now - globalNow if (gapInMilliseconds <= 2000) throw new Error('less than 2 seconds') return 'Hello' } const result = await waitFor(getByText) expect(result).toBe('Hello') }) }) Intenté arrojar un error cuando la devolución de llamada está llamando durante 2 segundos y devolver "Hola" después de eso, pero la devolución de llamada está llamando solo una vez y la prueba está fallando. ¿Qué pasé por alto aquí o un enfoque diferente para probar la parte de reintento de waitFor ?
it('should upload a pdf on "Upload voucher here" text click', async () => { const { getByText } = mountComponent({ certificate: { certificateName: 'Computer science', voucherStatus: VOUCHER_STATUS.OUTSTANDING_VOUCHER } }) const fileName = 'hello.pdf' const file = new File(['"(⌐□_□)"'], fileName, { type: 'application/pdf' }) const uploadText = getByText('Upload voucher here') fireEvent.change(uploadText, { target: { files: [file] } }) await waitFor(() => { expect(getByText('hello.pdf')).toBeInTheDocument() }) })Archivo de prueba para fileUpload y funciona bien.
{ selectedFile && ( <StyledFileName> {selectedFile.name} </StyledFileName> ) } Un fragmento en el componente, donde selectedFile es un estado para almacenar el archivo seleccionado por el usuario ( event.target.files[0]) ).