I have a React component that listen to beforeinstallprompt event to handle PWA app installation. It has an effect hook like this:
useEffect(() => {
window.addEventListener('beforeinstallprompt', handleBeforeInstallPromptEvent);
return () => {
window.removeEventListener('beforeinstallprompt', handleBeforeInstallPromptEvent);
};
}, [handleBeforeInstallPromptEvent]);
The handler handleBeforeInstallPromptEvent do some logic to show a banner asking the user to install the application if it has not already been installed.
To test this behaviour I created this jest test but it is not calling the event handler and consequently not showing the alert.
Am I missing something?
it('should render install app alert if not yet installed', async () => {
const event = createEvent('beforeinstallprompt', window, {
userChoice: new Promise((res) => res({ outcome: 'accepted', platform: '' })),
prompt: () => new Promise((res) => res(undefined)),
});
render(<InstallApp />);
await act(async () => {
fireEvent(window, event);
});
expect(screen.getByText(/Install app!/g)).toBeVisible();
});
I found the problem. The describe test block has this setup/teardown configuration that is preventing the events to be caught
beforeAll(() => {
window.addEventListener = jest.fn();
window.removeEventListener = jest.fn();
});
afterAll(() => {
(window.addEventListener as any).mockClear();
(window.removeEventListener as any).mockClear();
});