I have code like (kept only relevant code)
function App() {
const [values, setValues] = useState([]);
async function onUpload(event) {
if (event?.target.files?.length) {
const data = await event.target.files[0].text();
const json = JSON.parse(data);
setValues(json);
} else {
throw new Error('couldnt get files');
}
}
return (
<div>
{Boolean(!values.length) && (
<input data-testid="upInput" accept="application/JSON" type="file" onChange={onUpload} />
)}
{Boolean(values.length) && (
<div data-testid="handler">
<ValuesHandler values={values} />
</div>
)}
</div>
);
}
Now I want to test that values
are set correctly when the user uploads a file, and that ValuesHandler
is then present in the page.
I am trying in this direction in my App.test.tsx
import user from '@testing-library/user-event';
import someValues from '../somefile.json';
import { render } from '@testing-library/react';
test('should pass', () => {
const { getByTestId, queryByTestId } = render(<App />);
const str = JSON.stringify(someValues);
const blob = new Blob([str]);
const file = new File([blob], 'values.json', {
type: 'application/JSON',
});
const input = getByTestId('upInput');
user.upload(input, file);
const handler = queryByTestId('handler');
expect(handler).toBeTruthy();
});
This fails with handler being null.
The main suspect is that this line is not working in jest. Or I am not handling it properly.
const data = await event.target.files[0].text();
I am thinking about mocking the Blob.text
method to return the content of the file directly.. Not sure how though.