Data Crusader
Data Crusader

Reputation: 434

How to run basic test using karma (testacular)

I've been playing with jasmine recently in order to start incorporating tests in my projects. All seemed to work fine until, I wanted to automate the workflow with karma (previously Karma).

In my src directory, I have simple Calculator Object with a couple of simple methods: function Calculator() { };

var current = 0;

Calculator.prototype.add = function() {
if (arguments.length < 2) { 
    // we only have one arguments
    current += arguments[0];
    return current;
} else { 
    // more than one arguments
    for( var i in arguments ) 
        current += arguments[i];
    return current;
}
};

Calculator.prototype.substract = function() {
var currentValue = arguments[0];

for ( var i = 1; i < arguments.length; i++ ) 
    currentValue -= arguments[i];   
return currentValue;
};

Calculator.prototype.reset = function() {
window.current = 0;
}

Then in my spec file, I do have the following ( all tests passes without Karma ):

var calculator = new Calculator();

describe('Calculator', function() {
beforeEach(function() {
    window.current = 0;
});

describe('When adding numbers', function() {
    it('should store the current value at all times', function() {
        expect(window.current).toBeDefined();
    });

    it('should add numbers', function() {
        expect(window.calculator.add(5)).toEqual(5);
        expect(window.calculator.add(10)).toEqual(15);
    });

    it('should add any number of numbers', function() {
        expect(calculator.add(1, 2, 3)).toEqual(6);
        expect(calculator.add(1, 2)).toEqual(9);
    })
});

describe('When substracting numbers', function() {
    it('should substract any number of numbers', function() {
        expect(calculator.substract(5, 3)).toEqual(2);
    });
});

it('should reset the current value back to zero', function() {
    window.current = 20;
    calculator.reset();

    expect(window.current).toEqual(0);

    calculator.add(5);
    calculator.add(20);
    expect(window.current).toEqual(25);

    calculator.reset();
    expect(window.current).toEqual(0);
});
});

When I run karma start, I get the following: Chrome 28.0 (Mac) ERROR Uncaught ReferenceError: Calculator is not defined at /Users/roland/learning/jasmine/jasmine-standalone-1.3.1/spec/calculator_spec.js:1

Thank you for the help!

Upvotes: 1

Views: 3133

Answers (1)

jharding
jharding

Reputation: 1414

It seems like you're not loading the file that has Calculator or perhaps it's being loaded after the spec file. In your Karma configuration file, you'll want to do something like this:

files = [
  'path/to/calculator.js',
  JASMINE,
  JASMINE_ADAPTER,   
  'path/to/calculator_spec.js'
];

Upvotes: 2

Related Questions