首页 > 解决方案 > 如何在 Karma 单元测试中设置常量

问题描述

我在 Angular 1 中有这段代码。还有用 Karma 编写的测试用例。在这里,我已经涵盖了所有行。但是“如果”条件正在降低分支覆盖率。不知何故,我必须用“虚假”条件对其进行测试。

没有得到如何将“之后”常量作为未定义传递。

$scope.$on('klresource-bag.drop-model', (event, el, container) => {
    const changedIndex = domIndexOf(el[0], container);
    const changed = $scope.resources[changedIndex];
    const after = $scope.resources[changedIndex - 1];
    let afterId = 0;

    if (!isUndefined(after)) {
        afterId = after.model_resource.id;
    }

    $scope.$save(() => {
        const s = KLResource.sort({
        id: changed.model_resource.id,
        after: afterId,
        }, {});

        return s.$promise;
    });
});

这是我的单元测试用例。

describe('klresource-bag', () => {
    it('Checks the event "klresource-bag.drop-model"', () => {
        scope.$save = () => {};

        spyOn(Array.prototype.indexOf, 'call').and.returnValue(1);
        spyOn(scope, '$save').and.callFake(func => func());
        spyOn(KLResource, 'sort').and.returnValue({ $promise: {} });

        scope.$broadcast('klresource-bag.drop-model', {}, [{}], {});

        scope.$apply();

        expect(Array.prototype.indexOf.call).toHaveBeenCalled();
        expect(scope.$save).toHaveBeenCalledWith(jasmine.any(Function));
        expect(KLResource.sort).toHaveBeenCalledWith(jasmine.any(Object), jasmine.any(Object));
    });
});

我尝试在我的单元测试中设置它,但它抛出错误:

scope.resources = undefined;

标签: angularjskarma-jasmine

解决方案


推荐阅读