Here’s a few quick tip for the users of Jest out there!
Environment Variables
If you’re using environment variables that need to be loaded in before your tests run, you can use the –config flag. This flag will allow you to pass in environment variables. Example:
1 2 3 4 5 6 |
(async function () { console.log('Running Jest Setup init') // put all process env vars here process.env.TESTING = true }() // this function will evoke immediately |
1 2 3 4 5 6 7 |
module.exports = { ... 'setupFiles': [ './jest-setup.js' ] ... } |
Mocking Modules vs Mocking Specific Functions
When referring to external libraries, use jest.mock
. This is a very powerful function that will mock all exported methods from a module. You can think of it like a window in front of a store. You can see all of the items inside, but you don’t interact with them directly. For more info, check out this link from the Jest docs
Reseting Modules
One of the most annoying things about testing is always having to clean up state after your done. It’s like being a kid again and having to clean your room every day before your friends can come over, even though they were the ones who made it dirty yesterday. Luckily Jest makes this really easy thanks to the resetModules() function. More info can be found at this link. This comes in handy extremely often, don’t be afraid to use it a lot!
FIN
That’s it! Hopefully you took away on or two things from this post. If you’d like to learn more about testing, you can check out my other post on it here: Tests: 5 Tips to Make Coding Less Stressful Jest is a great framework, and if you have any questions about it, please leave a comment below!