A project created to test date mocking in applications running in docker containers. The project uses the libfaketime library which intercepts various system calls that programs use to retrieve the current date and time.
- I created a custom docker image where I installed the
libfaketimelibrary and created a.faketimercfile which is used to set the date. - I have configured the
apiservice in thedocker-compose.ymlfile where I declared that the date should be taken from the/home/node/.faketimercfile located in the docker container. - During automated tests, I change the content of the
/home/node/.faketimercfile by which the date that thenew Date()call returns changes.
- I created a custom docker image where I installed the
libfaketimelibrary. - I have configured the
databaseservice in thedocker-compose.ymlfile where I declared that the date should be taken from theFAKETIMEenvironment variable declared in the docker container. - During automated tests, I run the
SELECT NOW();query to return the date that PostgreSQL server sees.
- I created a custom docker image where I installed the
libfaketimelibrary. - I have configured the
cacheservice in thedocker-compose.ymlfile where I declared that the date should be taken from the/home/node/.faketimercfile located in the docker container. - During automated tests, I run the queries against redis cache and validate that the cache is being correctly cleared and set.
In order to test how the library works, I wrote automated tests in the src/app.controller.spec.ts file. To run the tests follow these steps:
- Start the docker containers via the
yarn upcommand. - Connect to the terminal in the container running the Node.js application via the
yarn shellcommand. - Run automated tests via the
yarn testcommand.
- Mocking dates in Node.js doesn't seem like the best solution to me. It works, but causes the test runner
Jestto show incorrect test execution time results (e.g. -720000 seconds). I think that for mocking dates in Node.js it would be better to use the mockdate library, as it does not affect the behavior ofJestand is simpler to set up. - Mocking dates in PostgreSQL seems to work without problems and can be a good solution if we want to test SQL queries that use time functions (e.g.
NOW()). - Mocking dates in Redis seems to work without problems and can be a good solution if we want to test the application that manages the cache.