AngularJS + Karma(Testacular)
我正在尝试在Karma为基于AngularJS的Web应用程序创建我的第一个单元测试。 我正在使用Jasmine作为测试框架。
我的单元测试看起来像:
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"]);
        });
    });
});
现在,当我运行测试时,出现以下形式的错误:
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
这个期望的LHS是一个在控制器范围内定义的变量。 可以看出,价值已被拿起,并且比较也似乎是正确的 - 但卡玛报告这是一个失败/错误。
任何想法为什么?
  那么这是因为在javascript表达式['val']===['val']总是评估为false。  因此,业力使用相同的东西来比较值,并且它也失败了。  最简单的解决方案,将这样比较它们: 
var values = scope.values[0].values;
expect(values.toString()).toBe(["M", "F"].toString());
或者你可以做这样的事情:
var values = scope.values[0].values;
expect(values.length).toBe(2);
expect(values).toContain('M');
expect(values).toContain('F');
或者,如果订单也很重要:
var values = scope.values[0].values;
expect(values.length).toBe(2);
expect(values[0]).toBe('M');
expect(values[1]).toBe('F');
  而不是使用匹配器toBe使用toEqual 
  Jasmine's toBe在Javascript中使用===运算符。  toEqual使用巧妙比较数组的自定义函数。 
有几件事你可能想在这里改变。 除非你有充分的理由,否则不应该真正嵌套描述。 你在beforeEach中错误地实例化了你的控制器(认为DI是角度的)。 另外,当您可能指“toEqual”时,您正在使用“toBe”。 试试这个代码:
 (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/39107.html
                        上一篇: AngularJS + Karma (Testacular)
下一篇: Should I be using @Controller classes when doing Spring web flow
