AngularJS + Karma (Testacular)
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 LHS 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?
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;
expect(values.length).toBe(2);
expect(values).toContain('M');
expect(values).toContain('F');
Or if order is important as well:
var values = scope.values[0].values;
expect(values.length).toBe(2);
expect(values[0]).toBe('M');
expect(values[1]).toBe('F');
Instead of using the matcher toBe
use toEqual
Jasmine's toBe
uses the === operator in Javascript. toEqual
uses a custom function which smartly compares arrays.
There are a couple of things you might want to change here. shouldn't really nest describes unless you have a good reason. You are incorrectly instantiated your controller in the beforeEach (think DI in angular). Also, you are using "toBe" when you probably mean "toEqual". Try this code:
(function() {
'use strict';
describe('MainController', function(){
var controller;
var scope;
beforeEach(module('MY_APP'));
beforeEach(inject(function($controller) {
scope = {};
controller = $controller('MainController', {$scope: scope})
}))
it('should be defined.', function () {
expect(controller).toBeDefined();
});
it('should have correct gender values.', function() {
expect(scope.values[0].values).toEqual(["M", "F"]);
})
})
链接地址: http://www.djcxy.com/p/39108.html