Testing showOpenFilePicker in vitest
I had a need to test window.showOpenFilePicker() which is something that really only works in the latest chrome and edge versions. A lot of other browsers just don’t support it (yet).
The method under test ideally should return a promise. However, testing after a click action that should open it throws an error. Subsequently it doesn’t show up in the DOM generated by RTL and the test fails.
What I can spy on is the implementation for showOpenFilePicker with:
describe('test suite', () => {
vi.stubGlobal('showOpenFilePicker', vi.fn());
it('should be some test', () => {
const filePickerSpy = vi.spyOn(window, 'showOpenFilePicker');
render(<SomeComponent />)
const openBtn = await screen.findByRole('button');
await userEvent.click(openBtn);
expect(filePickerSpy).toHaveBeenCalled();
});
}
This will let the filepicker show for the test and be available for assertions. In hindsight it seems to be fairly obvious, but at the time it was frustrating to deal with a feature that isn’t widely available yet.