Testing Considerations
In order to write tests that include IdleTimer, a few things will need to be mocked. Examples will be provided for the jest framework and the testing-library utilities, but the principles can be applied to any framework.
To keep your tests clean and modular, you will want to create a startup script
and add it to the setupFilesAfterEnv
section of your jest.config.js
or package.json
.
We will assume the setup file is called test.setup.js
for the following implementation.
Mock Timers#
If you are using worker thread timers, you can mock them for your testing environment. IdleTimer exposes a function to do this for you.
In your test.setup.js
, add the following:
import { createMocks } from 'react-idle-timer'beforeAll(createMocks)
This will have jest or your test runner of choice use the main thread timers for testing.
Mock MessageChannel#
IdleTimer uses MessageChannel
for the cross tab messaging layer internally. This is not mocked by default
in js-dom
. If you are using the cross tab feature, you will need to mock the global.
Add the following to your test.setup.js
.
import { MessageChannel } from 'worker_threads'import { cleanup } from '@testing-library/react'beforeAll(() => {// @ts-ignoreglobal.MessageChannel = MessageChannel})afterAll(cleanup)
If you are using Typescript you will have to either ignore the global assignment
or extend the global name space for your test runner. Since you are unlikely to
need types for MessageChannel, // @ts-ignore
will suffice.
Full Mock#
Here is the full mock requirements to test with IdleTimer.
//// jest.config.js//export default {...otherOptions,setupFilesAfterEnv: ['./test.setup.js']}
//// test.setup.js//import { createMocks } from 'react-idle-timer'import { MessageChannel } from 'worker_threads'import { cleanup } from '@testing-library/react'beforeAll(() => {createMocks()global.MessageChannel = MessageChannel})afterAll(cleanup)
With this setup script, you will be able to fully test your application with IdleTimer. If you need more examples, you can check out the test suite for IdleTimer itself.