-
-
Notifications
You must be signed in to change notification settings - Fork 145
Cypress testing #288
-
Hello everyone,
I'm trying to test with Cypress that the idle timeout modal appears after 15 min of user inactivity.
I'm using cy.clock and cy.tick to avoid waiting for actual 15 min
const now = new Date();
cy.login(creds);
cy.clock(now);
cy.tick(IDLE_TIMEOUT);
cy.findByTestId('app-idle-timeout-modal').should('exist');
Modal doesn't appear after cy.tick(IDLE_TIMEOUT) and test fails.
Seems like cy.clock doesn't override timing functions of react-idle-timer and the modal will appear after actual 15 min.
Here is my idle timer instantiation:
const AppIdleTimeoutModal: React.FC = () => {
const { logout } = auth0();
const [isOpen, setOpen] = useState(false);
const [remainingTime, setRemainingTime] = useState(0);
const onPrompt = () => {
setOpen(true);
setRemainingTime(PROMPT_TIMEOUT);
};
const onLogout = () => {
logout();
setOpen(false);
};
const onIdle = () => {
onLogout();
};
const onMessage = (e: string) => {
if (e === LOGOUT_MESSAGE) {
onLogout();
}
};
const { activate, getRemainingTime, isPrompted, message } = useIdleTimer({
onPrompt,
onIdle,
onMessage,
timeout: IDLE_TIMEOUT,
promptTimeout: PROMPT_TIMEOUT,
crossTab: true,
syncTimers: 200,
timers: workerTimers
});
const logoutWithMessage = () => {
message(LOGOUT_MESSAGE);
onLogout();
};
const onStayActive = () => {
activate();
setOpen(false);
};
useEffect(() => {
const interval = setInterval(() => {
if (isPrompted()) {
setRemainingTime(getRemainingTime());
}
}, 1000);
return () => {
clearInterval(interval);
};
}, [getRemainingTime, isPrompted]);
return (
<Dialog open={isOpen}>
<div>{remainingTime}</div>
<Button onClick={() => logoutWithMessage()}>Logout</Button>
<Button onClick={() => onStayActive()}>Stay active</Button>
</Dialog>
);
};
Is there any way to test it?
Thanks for any tips!
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 2 replies
-
Ah okay, you are using workerTimers. You are going to need to call createMocks() before your tests. That will switch out your timers to be using native timers.
https://idletimer.dev/docs/getting-started/testing#mock-timers
Let me know if that resolves the issue.
Beta Was this translation helpful? Give feedback.
All reactions
-
Im not familiar with cypress, but if there is a place where you turn on fake timers, you will want to call createMocks() before that. Otherwise just call it as early as possible.
Beta Was this translation helpful? Give feedback.
All reactions
-
I'm still experiencing issues with react-idle-timer and Cypress, even after adding createMocks(). Is there a specific way to ensure the mock initialization timing aligns correctly, or could Cypress's automatic waiting mechanisms be interfering? Any guidance on resolving this would be greatly appreciated.
Beta Was this translation helpful? Give feedback.