Jasmine Unit Test For AngularJS sample using Reshaprer and Chutzpa as test runner

Standard

GitHub Repository:  GitHub Link

Jasmine Unit Test For AngularJS sample using Reshaprer and Chutzpa as test runner

For installing Chutzpaa:

For installing Resharper:

pastedimage 2

Jasmine Cheatsheet

describe("A suite", function() {
  it("contains spec with an expectation", function() {
    expect(true).toBe(true);
  });
});

Expectations

expect(true).toBe(true)
expect(true).not.toBe(true)

expect(a).toEqual(bar)

expect(message).toMatch(/bar/)
expect(message).toMatch('bar')

expect(a.foo).toBeDefined()
expect(a.foo).toBeUndefined()
expect(a.foo).toBeNull()

expect(a.foo).toBeTruthy()
expect(a.foo).toBeFalsy()

expect(message).toContain('hello')

expect(pi).toBeGreaterThan(3)
expect(pi).toBeLessThan(4)
expect(pi).toBeCloseTo(3.1415, 0.1)

expect(func).toThrow()

Blocks

beforeEach(function() { ... });
afterEach(function() { ... });

Pending

xit("this is a pending test", function() { ... })
xdescribe("this is a pending block", function() { ... })

Spies

spyOn(foo, 'setBar')
spyOn(foo, 'setBar').andReturn(123)
spyOn(foo, 'getBar').andCallFake(function() { return 1001; })
foo.setBar(123)

expect(foo.setBar).toHaveBeenCalled()
expect(foo.setBar).toHaveBeenCalledWith(123)
expect(foo.setBar.calls.length).toEqual(2)
expect(foo.setBar.calls[0].args[0]).toEqual(123)

Creating spies

stub = jasmine.createSpy('stub')
stub("hello")

expect(stub.identity).toEqual("stub")
expect(stub).toHaveBeenCalled()

Async

it("should run async", function() {
  var flag = false, value = 0;

  runs(function() {
    setTimeout(function() { flag = true; }, 500);
  });

  waitsFor(function() {
    value++;
    return flag;
  }, "increment", 750);

  runs(function() {
    expect(value).toBeGreaterThan(0);
  });
});

HTML runner

var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 250;

var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);

$(function() { jasmineEnv.execute(); });

Jasmine jQuery

Jasmin jQuery.

expect($('#id')).toBe('div')
expect($('input[type=checkbox]')).toBeChecked()
expect($('input[type=checkbox]')).toBeDisabled()
expect($('input[type=checkbox]')).toBeFocused()
expect($('#menu ul')).toBeEmpty()

expect($('#toolbar')).toBeHidden()
expect($('#toolbar')).toBeVisible()

expect($('#popup')).toHaveCss({ margin: "10px" })
expect($('option')).toBeSelected()

expect($('.foo')).toExist()

expect($('a')).toHaveAttr('rel')
expect($('a')).toHaveAttr('rel', 'nofollow')

expect($('a')).toHaveClass('rel')
expect($('a')).toHaveId('home')

expect($('a')).toHaveHtml('<span></span>')
expect($('a')).toContainHtml('<span></span>')
expect($('a')).toHaveText('hi')

expect($form).toHandle('submit') // event
expect($form).toHandleWith('submit', onSumbit)

Event spies

spyOnEvent($('#some_element'), 'click');
$('#some_element').click();
expect('click').toHaveBeenPreventedOn($('#some_element'));
expect('click').toHaveBeenTriggeredOn($('#some_element'));

Below images will highlight new changes in ngninja project

  • Directory Structure
  • Resharper test Runner
  • Chutzpa test runner

pastedimage

How to code Jasmine Test Case

  • Mention test file name
  • Mock all dependencies for module which you are testing
  • mention angular module name for which you are writing test cases
  • Inject dependencies and initialize all variables
  • Write unit test for each functionality

P.S. I have written unit test cases for Candidate Module(Controller, Service, main Candidate file and Shared http service, total 18 Unit test cases)

pastedimage 1

/// <reference path="../../../../lib/angular/angular.js" />
/// <reference path="../../../../lib/angular/angular-mocks.js" />
/// <reference path="../js/onBoardingApp.candidate.controller.js" />

describe('onBoardingApp-candidate-controllers', function () {
    var candidateService, controller;

    beforeEach(function () {

        module('onBoardingApp.candidate.controllers');

        module(function ($provide) {
            $provide.value('candidateService', {
                getAllCandidates: function () {
                    return {
                        then: function () { return {}; },

                    }
                }
            });
        });

        inject(function ($controller, _candidateService_) {
            candidateService = _candidateService_;
            controller = $controller("CandidateController", {});
        });
    });

    it('should contain factory', function () {
        expect(candidateService).not.toEqual(null);
    });

    it('should return tempValueForUnitTest', function () {
        expect(controller.tempValueForUnitTest).toEqual("testing123");
    });

    it('should return testFunctionForUnitTesting function', function () {
        expect(controller.testFunctionForUnitTesting()).toEqual("test");
    });

    it('should add candidate record', function () {
        controller.candidates = [];
        controller.newCandidate =
        {
            'candidate_id': '1',
            'first_name': 'Scott',
            'middle_initial': 'AA',
            'last_name': 'Gurthie',
            'email': 'h@aa.com',
            'expected_salary': '15000'
        };        
       controller.add();
       expect(controller.candidates[0].email).toEqual('h@aa.com');
    });

    it("should cancel candidate's record to be updated", function () {
        controller.cancelEdit(2);
        expect(controller.currentEdit[2]).toBeFalsy();
    });

    it('should edit candidate record', function () {
        var candidate =
        {
            'candidate_id': '1',
            'first_name': 'Scott',
            'middle_initial': 'AA',
            'last_name': 'Gurthie',
            'email': 'h@aa.com',
            'expected_salary': '15000'
        };
        controller.edit(candidate);
        expect(controller.itemToEdit.first_name).toBe('Scott');
    });

    it("should find candidate by id", function () {

        controller.candidates = [
            {
                'candidate_id': '1',
                'first_name': 'Scott',
                'middle_initial': 'AA',
                'last_name': 'Gurthie',
                'email': 'h@aa.com',
                'expected_salary': '15000'
            }, {
                'candidate_id': '2',
                'first_name': 'Brett',
                'middle_initial': 'BB',
                'last_name': 'John',
                'email': 'h@bb.com',
                'expected_salary': '55000'
            }
        ];

        expect(controller.findCandidate(2)).toEqual('1');
    });

    it('should save candidate record after update', function () {
        var candidate =
        {
            'candidate_id': '1',
            'first_name': 'Scott111',
            'middle_initial': 'AA111',
            'last_name': 'Gurthie111',
            'email': 'h@aa111.com',
            'expected_salary': '15000111'
        };
        controller.edit(candidate);
        controller.save(candidate);
        expect(controller.itemToEdit.first_name).toBe('Scott111');
    });

});
Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s