Vitest - Optional Pass in Timeout
03/01/2025, SatCustom Timeout
In the situation where your tests might actually run slower on another person's machine, you should give them an option to increase the timeout to prevent timeout failures.
At first glance, you might do something like this to run the command to accept a timeout value.
npm run test -- --testTimeout=50000
However, the following is problematic because the npm script was not able to pass in this value into vite test file context and the process.argv
variable didn't yield any values.
To get around this issue, you can set your vite.config.ts
file
to read in an environment variable and use that value as the custom timeout.
// vitest.config.ts
import { defineConfig } from 'vite'
// Use the default timeout amount if no custom value is
// provided in the enviroment variable
const defaultTimeout = 100000;
const initialReadTimeout = typeof process.env.VITEST_TIMEOUT == "string" ?
process.env.VITEST_TIMEOUT : `${defaultTimeout}`;
const parsedNegotiatedTimeout = parseInt(initialReadTimeout, 10);
const finalTimeout = parsedNegotiatedTimeout > 0 ?
parsedNegotiatedTimeout : defaultTimeout;
export default defineConfig({
test: {
testTimeout: finalTimeout,
coverage: {
reporter: ['text', 'json', 'lcov'],
}
},
});
This will allow to define a VITEST_TIMEOUT
environment variable to specify
a custom timeout value before running the test to increase the timeout value.
When the custom timeout value isn't defined, it will fall back to using a default value defined in the vite.config.ts
file.
The general finalTimeout
will be taken as a global timeout value.
VITEST_TIMEOUT=200000 npm run test