Test process.env with Jest

The way I did it can be found in this Stack Overflow question. It is important to use resetModules before each test and then dynamically import the module inside the test: describe(‘environmental variables’, () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetModules() // Most important – it clears the cache process.env = { …OLD_ENV … Read more

How do I set a mock date in Jest?

As of Jest 26 this can be achieved using “modern” fake timers without needing to install any 3rd party modules: https://jestjs.io/blog/2020/05/05/jest-26#new-fake-timers jest .useFakeTimers() .setSystemTime(new Date(‘2020-01-01’)); If you want the fake timers to be active for all tests, you can set timers: ‘modern’ in your configuration: https://jestjs.io/docs/configuration#timers-string EDIT: As of Jest 27 modern fake timers is … Read more

How do you test for the non-existence of an element using jest and react-testing-library?

From DOM Testing-library Docs – Appearance and Disappearance Asserting elements are not present The standard getBy methods throw an error when they can’t find an element, so if you want to make an assertion that an element is not present in the DOM, you can use queryBy APIs instead: const submitButton = screen.queryByText(‘submit’) expect(submitButton).toBeNull() // … Read more

How to use ESLint with Jest

The docs show you are now able to add: “env”: { “jest/globals”: true } To your .eslintrc which will add all the jest related things to your environment, eliminating the linter errors/warnings. You may need to include plugins: [“jest”] to your esconfig, and add the eslint-plugin-jest plugin if it still isn’t working.

Message “Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout”

The timeout you specify here needs to be shorter than the default timeout. The default timeout is 5000 and the framework by default is jasmine in case of jest. You can specify the timeout inside the test by adding jest.setTimeout(30000); But this would be specific to the test. Or you can set up the configuration … Read more