我正在使用chai来尝试和单元测试我在网上找到的一个验证函数。此验证函数正在“react-final-form”组件中使用。
下面是我从这里得到这个验证器函数的地方:
https://youtu.be/OEg8jm-NbQ0?t=567
import chai, { expect } from "chai";
import chaiEnzyme from "chai-enzyme";
chai.use(chaiEnzyme());
const required = (value) => value === '' ? 'This is required.' : undefined;
const url = (value) => value && !(/^\/[a-z0-9]+$|[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi).test(value) ? 'This does not appear to be a link.': undefined;
const composeValidators = (...validators) =>
(value) =>
validators.reduce((error, validator) => error || validator(value), undefined);
let value = '';
describe("Forms", () => {
describe("Final form", () => {
describe("Utils", () => {
it("Returns correct error message when form field value is empty and field is required", () => {
expect(composeValidators(required)).to.equal('This is required.');
});
it("Returns correct error message when form field value is not empty and field should be a url", () => {
value = 'not empty';
expect(composeValidators(url)).to.equal('This does not appear to be a link.');
});
});
});
});目前,这两个断言都返回函数,而不是我期望的字符串值,我不确定为什么。任何关于如何修复此测试的想法都将不胜感激。
发布于 2019-10-06 19:09:41
我确实喜欢最终的形式。它确实帮助我们深入了解了如何使用currying函数。所以,你从final form中抓取的例子,我个人在字段中使用过。
composeValidators(required)(value)Currying是一个奇怪的概念,你可以在不需要它的情况下使用它,所以不要为第一眼看不懂它而烦恼。
让我们来看一下签名:
const composeValidators = (...validators) => (value) =>
第一个函数接受X个属性或验证规则。你已经把那部分写下来了。第二个函数now需要一个值。您可能见过它与Field的validate属性一起使用。如果您查看FieldProps的文档(参见下面的链接),您将看到它接受一个函数并向其传递3个参数、值、allValues和元,而不仅仅是值。这可以帮助您编写更好的验证规则,以考虑有关该字段的更多信息。无论如何,当final-form使用它时,它采用以下形式:
composeValidators(required)(value, allValues, meta)我并不期望这篇文章马上就有意义,但它应该会帮助你思考currying的一个特定用例,它有一些高级选项。享受最终的形式!
https://final-form.org/docs/react-final-form/types/FieldProps
https://stackoverflow.com/questions/58251185
复制相似问题