May 26, 2021

Mock Intl and Date globals in Jest

In Javascript land, mocking the browser global objects can be a bit of a pain for tests. Searching StackOverflow gives plenty of complicated answers. Some suggesting using 3rd party mock libraries. Some that overwrite the global object itself…. But Jest already has this capability built-in and it isn’t so bad:

So let’s say you have a method that gets the user’s timezone or the timezone offset. (the timezone offset is used sometimes since IE11 doesn’t support easily reading the timezone, but I digress)

Now to test this, we’ll need to mock out both the Intl and Date Javascript globals. We can do this using Jest’s spyOn method to temporarily replace the global method with our own implementation. Notice that we setup the spy in the beforeEach and reset everything in the afterEach. The setup works something like this:

But that’s it! No need to import an extra library. This is all supplied directly in Jest itself!

About the Author

Object Partners profile.
Leave a Reply

Your email address will not be published.

Related Blog Posts
Natively Compiled Java on Google App Engine
Google App Engine is a platform-as-a-service product that is marketed as a way to get your applications into the cloud without necessarily knowing all of the infrastructure bits and pieces to do so. Google App […]
Building Better Data Visualization Experiences: Part 2 of 2
If you don't have a Ph.D. in data science, the raw data might be difficult to comprehend. This is where data visualization comes in.
Unleashing Feature Flags onto Kafka Consumers
Feature flags are a tool to strategically enable or disable functionality at runtime. They are often used to drive different user experiences but can also be useful in real-time data systems. In this post, we’ll […]
A security model for developers
Software security is more important than ever, but developing secure applications is more confusing than ever. TLS, mTLS, RBAC, SAML, OAUTH, OWASP, GDPR, SASL, RSA, JWT, cookie, attack vector, DDoS, firewall, VPN, security groups, exploit, […]