【问题标题】:How to solve my unit test issue in my case [closed]在我的案例中如何解决我的单元测试问题[关闭]
【发布时间】:2015-01-28 22:41:27
【问题描述】:

我正在尝试为我的代码编写单元测试,我需要一些指导。

我的文件中有类似的东西

//inside my 'testCtrl' I have
$scope.calculateTime = function() {
    var date = new Date();
    $scope.currentYear = date.getFullYear();
}

$scope.calculateLastYear = function() {
    $scope.currentYear = $scope.currentYear - 1;
}

我的测试文件。

describe('Controller: testCtrl', function(){
    beforeEach(module('myApp'));
    beforeEach(inject(function(_$controller_, _$rootscope_) {
        scope._$rootScope.$new();

        testCtrl = _$controller_('testCtrl', {
            $scope:scope 
        })
    })

    //for some reason, every tests I write below are passed even  
    //though it should fail

      it('should get the last year'), function() {
            expect(scope.currentYear).toBe('text here….') //<-- it should fail but   
                                                          //it passes
      };
})

我不知道如何编写测试来检查calculateLastYear 函数,我不知道为什么我的expect(scope.currentYear).toBe('text here….') 通过了。任何人都可以帮助我吗?非常感谢!

【问题讨论】:

  • beofreEach 应该是 beforeEach
  • 括号放错了地方。 it('应该得到最后一年'),
  • 不知道为什么这是题外话 - 有一个错字 - 但语法也有问题。

标签: javascript angularjs unit-testing karma-runner


【解决方案1】:

您的规范语法不正确。应该是这样(请原谅双关语):

it('should get the last year', function() {
            expect(scope.currentYear).toBe('text here….');
});

计算去年的规格:

  it('should get the last year', function() {
    $scope.currentYear = 2015;
    $scope.calculateLastYear();
    expect($scope.currentYear).toEqual(2014);
  });

【讨论】:

  • 谢谢,我错过了。你能帮我写一下calculateLastYear函数的测试吗? +1
  • it('应该计算去年', function() { $scope.currentYear = 2015; $scope.calculateLastYear(); expect($scope.currentYear).toEqual(2014); }) ;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-19
  • 2020-02-16
  • 1970-01-01
  • 2021-09-24
  • 1970-01-01
  • 2018-03-13
相关资源
最近更新 更多