1

在 ViewModel 中,我有一些属性需要和正则表达式验证(在同一属性上),如下所示:

// ...other properties...
MaxDays: ko.observable("").extend({
    required: { message: "You have to specify the maximum number of days." },
    pattern: {
        message: "Please enter a valid number.",
        params: '[0-9]+$',
        maxLength: 10
    }
}),
// ...other properties...

我正在使用 Jasmine 进行测试,我注意到如果我分配的值与表达式不匹配,则该值将被忽略,并且它会运行自己的“必需”测试,就好像该属性中没有数据一样。

// ... describe, other "it" statements, etc...
it("should complain if there's incorrect data", function () {

    viewModel.MaxDays("Zweiundzwanzig");

    expect(viewModel.errors().length).toBeGreaterThan(0);
    expect(viewModel.errors()).toContain('Please enter a valid number.');

    console.log(viewModel.errors());

});
// ...

当我运行测试时它失败了。错误集合充满了错误,但不是因为我输入了一个应该是数字的字符串。它失败了,因为它认为该属性是空的。我从“必需”而不是“模式”中收到错误消息:

在此处输入图像描述

有趣的是它可以在 UI 上运行,所以如果我在绑定到该属性的字段上输入字符串值,它将触发正则表达式验证并将正确的错误消息放在字段旁边。

谁能指出我在这里缺少什么?

4

1 回答 1

1

如果错误类型发生变化,knockout.validation.group.errors() 当前无法正确更新(请参阅https://github.com/ericmbarnard/Knockout-Validation/issues/218)。

我认为这是你的问题。尝试将“MaxDays”设置为正确的值,然后设置为无效值。如果那是您的问题,那应该可以解决测试。

于 2013-02-08T21:50:28.963 回答