单元测试指令错误 - 尝试分配给只读属性

时间:2016-12-19 14:54:54

标签: angularjs unit-testing jasmine karma-jasmine sinon

单元测试指令错误 - 尝试分配给只读属性

技术:Angular版本1.3和javascript with sinon

这是我在Git Bash中遇到的错误:

enter image description here

这是我正在测试的代码:

 angular.module("myApp.directives")
    .directive("checkList", ["lodash", function(lodash) {
        return {
            restrict: "E",
            scope: {
                filter: "="
            },
            templateUrl: "templates/components/check-list.html",
            link: function (scope, element) {
                scope.changeDetection = () : void => {
                    const listOfStrings = [];

                    lodash.forEach(scope.filter.options, function(option) {
                         if (option.selected) listOfStrings.push(option.name);
                    });

                    scope.filter.value = listOfStrings.length > 0 ? listOfStrings.join(",") : [];
                };

                scope.$watch("filter", (newValue, oldValue) => {
                    if (newValue) scope.changeDetection();
                } , true);
            }
        };
    }]);

这是我的单元测试:

"use strict";

describe("check list component:", function () {
    var rootScope;
    var element;
    var scope;
    var mockFilter = {
        "id": "underOffer" ,
        "value": [],
        "options": [
            {"Yes" : "Lease", "selected": false},
            {"name" : "No", "selected": false},
            {"name" : "Partial", "selected": true}
        ]
    };

    beforeEach(angular.mock.module("myApp.directives"));
    beforeEach(module("ngLodash"));

    beforeEach(inject(function($rootScope, $compile) {
        var rootScope = $rootScope;
        scope = $rootScope.$new();

        element = "<check-list filter=\"'" + mockFilter + "'\" ></check-list>";
        element = $compile(element)(scope);
        angular.element(document.body).append(element);

        scope.$digest();
        scope = element.isolateScope();

        scope.filter = mockFilter;
    }));

    it("should call changeDetection and add value to check list", function () {
        //Arrange
        var mockResponse = "Partial";

        //Act
        scope.$digest();

        //Assert
        expect(scope.filter.value).toEqual(mockResponse);
    });
});

注意:似乎是导致此问题的观察者。我基本上想要存根或忽略它,所以我可以测试changeDetection函数。

0 个答案:

没有答案