user109187 user109187 - 2 years ago 104
AngularJS Question

AngularJS + Karma (Testacular) - Unit Test failing

I am attempting to create my first unit test in Karma for an AngularJS based web application. I am using Jasmine as the testing framework.

My unit test looks like:

describe('FooBar', function() {

describe('FBCtrl', function() {
var scope, ctrl;

beforeEach(function() {
scope = {};
ctrl = new FBCtrl(scope);

it('should have correct gender values', function() {
expect(scope.values[0].values).toBe(["M", "F"]);

Now, when I run the test, I get an error in the following form:

Chrome 26.0 (Linux) FooBar FBCtrl should have correct gender values FAILED
Expected [ 'M', 'F' ] to be [ 'M', 'F' ].
Error: Expected [ 'M', 'F' ] to be [ 'M', 'F' ].
at null.<anonymous> //followed by the js file given has input to Karma

The L.H.S of this expectation was a variable defined inside a scope of a controller. As can be seen, the value has been picked up and the comparison also seems to be correct - yet Karma reports this as a failure / error.

Any idea why?

Answer Source

Well it is because in javascript expression ['val']===['val'] always evaluates to false. Therefore karma uses the same thing to compare values, and it fails as well. Easiest solution, will be to compare them like this:

var values = scope.values[0].values;
expect(values.toString()).toBe(["M", "F"].toString());

Or you can do something like this:

var values = scope.values[0].values;

Or if order is important as well:

var values = scope.values[0].values;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download