Recently a user asked in Filip Hric's Discord server how to pick a different test item daily to use in their Cypress tests.
An excellent question. Sometimes we have a lot of test items, but we want to pick a random one daily. Here is my solution:
- take the current timestamp and convert to the number of days since the start of JS epoch (1970)
- take the module of days vs test items, this gives you a test item's index. The index changes daily and "wraps" around to the first item when all items have been tested.
A sample code to pick an item:
1 | const now = new Date() |
🎁 You can find the full source code in the repo bahmutov/cypress-test-every-day.
Let's say the application is showing a randomized list of fruits. We know we want to eventually test every fruit from the JSON file test-fruits.json
1 | ["Apples 655", "Grapes 1001", "Pears 499"] |
Our spec file and test JSON file are placed in the repo folder:
1 | app/ |
Let's pick a random test fruit from the JSON file. We can read the file using cy.readFile command
1 | it('shows one of the fruits', () => { |
Tip: want to pick a new test item hourly? Divide the timestamp by the number of milliseconds in one hour.
Tip 2: want to pick consistent item locally and on the CI server? Use UTC timestamp.
Of course, if our test data comes from a JSON file, we can simply import it into our spec
1 | import testFruits from '../../test-fruits.json' |
Works the same way
For more on JSON fixtures, read my blog post Import Cypress fixtures.