如何使用Jasmine在$ scope范围内伪造一个方法

时间:2017-03-14 13:14:07

标签: angularjs jasmine

我继承了一些我试图开始工作的破碎测试。我们正在使用Angular 1.5和Jasmine。在一个真实的'控制器我们有以下几点:

function myfunction() {
  $scope.stop = function() {
     $interval.cancel(promise);
     $timeout.cancel(timeout);
  };
  .........

此函数在控制器顶部调用。

在我的测试文件中,我使用:

设置间隔和超时
 'use strict';

var $scope;
var $timeout;


describe('Pas', function(){
describe('PasController', function() {
    var $this;
    var $rootscope;
    var PasService;
    var $interval = jasmine.createSpy('$interval', $interval).and.callThrough();
    var $timeout = jasmine.createSpy('$timeout', $timeout).and.callThrough();

    beforeEach(module('CL.Pas'));

    beforeEach(inject(function (_$controller_, _$rootScope_, _PasService_, _$interval_, _$timeout_) {
        $rootscope = _$rootScope_;
        PasService = _PasService_;
        $interval  = _$interval_;
        $timeout = _$timeout_;

        var data = {
            "Id": "00000000-0000-0000-0000-000000000000",
            "SectionSlug": "string",
            "SectionName": "PAS",
            "Sections": [
                {
                    id: "00000000-0000-0000-0000-000000000001",
                    Mandatory: true,
                    description: "test 1",
                    name: "Section 1",
                    status: "Not Started"
                },
                {
                    id: "00000000-0000-0000-0000-000000000003",
                    Mandatory: false,
                    description: "test 3",
                    name: "Section 3",
                    status: "Started"
                },
                {
                    id: "00000000-0000-0000-0000-000000000002",
                    Mandatory: true,
                    description: "test 2",
                    name: "Section 2",
                    status: "Not Started"
                }
            ],
            Forms: []
        };

        spyOn(PasService, 'canSubmitMandatorySections').and.callFake(getFakePromise({Result: false}));
        spyOn(PasService, 'canSubmitOptionalSections').and.callFake(getFakePromise({Result: false}));
        spyOn($interval, 'cancel');
        spyOn($timeout, 'cancel');


        $this = _$controller_('PasController', {sections: data, PasService: PasService, canSubmitIndividual: true, $scope: $scope,  $timeout : $timeout, $interval: $interval});
    }));

    it('should split available sections', function () {
        $rootscope.$apply();

        expect($this.sections.mandatory.length).toEqual(2);
        expect($this.sections.optional.length).toEqual(1);
    });
});
});  

在我的测试运行时,我收到 TypeError:无法设置属性'停止'未定义。如何在我的测试中伪造这个?

尝试从 $ controller

设置$ this时,设置出错

1 个答案:

答案 0 :(得分:0)

我忘了实现范围$scope = $rootscope.$new();