Testing time-dependent features in JavaScript

Many applications use the current time in their functionality.  For example, they can show data for a certain period of time or show the current date within the application.  Writing functional tests for such applications can be tedious.  How do you write a repeatable test for functionality that only occurs on Thursdays?

For this purpose I wrote TimeShift.js.  It is a mock implementation of the normal Date constructor which allows you to set the current time and time zone.

Date = TimeShift.Date;
new Date().toString();
// => "Tue Jun 01 2010 17:00:00 GMT+0500"

This way you can write repeatable test cases that still depend on the current time.

In order to use the library in tests, you need to override the Date function or inject TimeShift.Date in its place in your code.  One option is to make a custom build that is used for testing, another is to inject the library using your test code.  Both of these have some disadvantages.  Using a custom test build means that you cannot run your tests on a production build, while test code may be too late to inject the library in case the app reads the date during startup.

Instead, in our project we opted to include the library in our main code base.  Whenever a cookie with a specific name is present, the Date object is overridden and the time and time zone are set based on the cookie value.  This allows easily setting up the time state before starting a test case.

With a few simple Cucumber step definitions creating time-independent test cases becomes a breeze:

  Given the current timezone is Europe/Berlin
    And the current time is 2012-06-01 14:00
This entry was posted in Coding, Cucumber, JavaScript, Testing and tagged , , , . Bookmark the permalink.

1 Response to Testing time-dependent features in JavaScript

  1. Pingback: Testing visual appearance with Cucumber + Watir | Code for Hire

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s