AngularJS + Karma(Testacular) - 单元测试失败

时间:2013-04-13 20:20:47

标签: angularjs karma-runner

我正在尝试在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

这种期望的L.H.S是在控制器范围内定义的变量。可以看出,该值已被提取并且比较似乎也是正确的 - 但是Karma将此报告为失败/错误。

知道为什么吗?

3 个答案:

答案 0 :(得分:4)

而不是使用匹配器toBe使用toEqual

Jasmine的toBe在Javascript中使用===运算符。 toEqual使用自定义函数,智能地比较数组。

答案 1 :(得分:2)

这是因为在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');

答案 2 :(得分:0)

您可能希望在此处更改一些内容。除非你有充分的理由,否则不应该真正描述。你在beforeEach中错误地实例化了你的控制器(想象角度为DI)。此外,您正在使用&#34; toBe&#34;当你可能意味着&#34; toEqual&#34;。试试这段代码:

 (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"]);
     })
})