在我的情况下,如何解决我的单元测试问题

How to solve my unit test issue in my case

本文关键字:我的 解决 问题 单元测试 何解决 情况下      更新时间:2023-09-26

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

我的文件中有一些东西,例如

//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….')通过了。谁能帮我?多谢!

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

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);
  });