How to start with TDD in ServiceNow

This time I would like to present how to create very first unit test and adapt TDD for creating scripts in ServiceNow.
I’m going to create two very simple script includes: Course and Student.
The course will be implemented three methods:
– addStudent
– getStudent
– removeStudent

Creating Unit Tests

Before we start with implementation of Course and Student classes we have to create Unit Tests.
In your ServiceNow instance go to: Automated Test Framework -> Test and click ‘New’. Let’s name this new test as ‘CourseSpec’.
Next add new Test Step and select: ‘Run Server Side Script’:

Script with simple unit tests:

(function(outputs, steps, stepResult, assertEqual) {
    describe('Course', function(){
    var course,
        thisStudent;
    
     beforeEach(function () {
        course = new Course();
        thisStudent = new Student();
    });
    
    it('should be able to add student', function () {

        course.addStudent(thisStudent);

        expect(course.getStudent(0)).toBe(thisStudent);
    });

    it('should be able to remove a student', function () {

        course.addStudent(thisStudent);
        course.removeStudent(0);

        expect(course.getStudent(0)).not.toBeDefined();
    });
});

})(outputs, steps, stepResult, assertEqual);
jasmine.getEnv().execute();

After saving you can run test – it should failed.

Test results:

Implementing Course and Student

Once you’re ready with the unit tests you can start creating Course and Student Script Includes.

The Student implemenation is very simple:

var Student = Class.create();
Student.prototype = {
    initialize: function() {
    },

    type: 'Student'
};

The Course class is a little bit more complicated:

var Course = Class.create();
Course.prototype = {
    initialize: function() {
        this.students = [];
    },
    
    addStudent: function(student){
        this.students.push(student);
    },
    
    getStudent: function(index){
        return this.students[index];    
    },
    
    removeStudent: function(index){
        this.students.splice(index,1);
    },
    type: 'Course'
};

Next you can run the unit tests again which should pass this time:

Leave a Reply

Your email address will not be published. Required fields are marked *