Quantcast
Channel: Code for Hire » JavaScript
Viewing all articles
Browse latest Browse all 2

Testing time-dependent features in JavaScript

$
0
0

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;
TimeShift.setTimezoneOffset(-300);
TimeShift.setTime(1275393600000);
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:

Background:
  Given the current timezone is Europe/Berlin
    And the current time is 2012-06-01 14:00


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images