Skip to content

Instantly share code, notes, and snippets.

@nelsonfncosta
Created September 3, 2021 08:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nelsonfncosta/858597a46e25068e6a6c05e0544a4ca5 to your computer and use it in GitHub Desktop.
Save nelsonfncosta/858597a46e25068e6a6c05e0544a4ca5 to your computer and use it in GitHub Desktop.
async promises test
import React from 'react'
import Dropzone from 'react-dropzone'
import { act, fireEvent, render, waitFor } from '@testing-library/react'
test('invoke onDragEnter when dragenter event occurs', async () => {
const file = new File([
JSON.stringify({ping: true})
], 'ping.json', { type: 'application/json' })
const data = mockData([file])
const onDragEnter = jest.fn()
const ui = (
<Dropzone onDragEnter={onDragEnter}>
{({ getRootProps, getInputProps }) => (
<div {...getRootProps()}>
<input {...getInputProps()} />
</div>
)}
</Dropzone>
)
const { container, rerender } = render(ui)
const dropzone = container.querySelector('div')
dispatchEvt(dropzone, 'dragenter', data)
await flushPromises(rerender, ui)
expect(onDragEnter).toHaveBeenCalled()
})
async function flushPromises(rerender, ui) {
await act(() => waitFor(() => rerender(ui)))
}
function dispatchEvt(node, type, data) {
const event = new Event(type, { bubbles: true })
Object.assign(event, data)
fireEvent(node, event)
}
function mockData(files) {
return {
dataTransfer: {
files,
items: files.map(file => ({
kind: 'file',
type: file.type,
getAsFile: () => file
})),
types: ['Files']
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment