使用 Jasmine 测试 Angular 的 $valid 和 $pristine 状态

Test Angular's $valid and $pristine states with Jasmine

我的 Jasmine 测试不喜欢在我的控制器中使用 $pristine$valid,并输出以下错误:

TypeError: 'scope[...].$pristine' is null or not an object

引发此错误的测试如下:

it('should validate values correctly', function () {
    var scp = ngElement.scope();

    var tests = [
        {
            valid: true,
            validationOptions: {
                required: true
            },
            value: '1'
        }
    ];

    $.each(tests, function (testIndex, testItem) {
        scp.name = 'test';
        scp.value = testItem.value;
        $.each(testItem.validationOptions, function (itemKey, itemValue) {
            scp[itemKey] = itemValue;
        });
        scp.change();
        expect(scp.valid).toBe(testItem.valid);
    });
});

$pristine 和 $valid 状态下控制器中的函数如下:

    // Field change behaviours
    scope.change = function () {
        validate();
        ...
    };

    // Field level validation function
    function validate () {
        // If the field does not have a value and is pristine, scope.valid is undefined.
        // Otherwise the field is validated
        if ((!scope.value || scope.value.length === 0) && scope[scope.name].$pristine) scope.valid = undefined;
        else scope.valid = scope[scope.name].$valid;

        ...
    }

当您在视图上定义表单时,表单控制器被注入到您的控制器中,其名称在表单的名称属性中指定。

由于您的单元测试不会创建实际视图,您唯一的选择是创建一个虚拟的 formcontroller 和您在作用域上手动访问的属性。像

scp.formName={};  // formName should be the same that you refer with `scope.name`
scp.formName.$pristine=true;  // set value according to the test
scp.formName.$valid=true;   // set value according to the test.

请记住,您不想测试表单指令是否正常工作。已经用框架测试过了,