[英]I'm trying to test a function that takes another function as a parameter
我正在使用 chai 嘗試對我在網上找到的驗證 function 進行單元測試。 此驗證 function 正在“react-final-form”組件內部使用。
這是我從以下位置獲得此驗證器 function 的地方:
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.');
});
});
});
});
目前這兩個斷言都返回 [function] 而不是我期望的字符串值,我不知道為什么。 任何有關如何修復此測試的想法將不勝感激。
我確實喜歡最終形式。 它確實有助於深入了解如何使用柯里化函數。 因此,您從我個人使用的最終表單中獲取的示例與字段。
composeValidators(required)(value)
Currying 是一個奇怪的概念,你不需要它就可以理解它,所以不要擔心乍一看不理解它。
讓我們看一下簽名:
const composeValidators = (...validators) => (value) =>
第一個 function 采用 X 個道具或驗證規則。 你已經把那部分記下來了。 現在,第二個 function 需要一個值。 您可能看到它與 Field 的 validate 道具一起使用。 如果您查看 FieldProps 的文檔(請參閱下面的鏈接),您會看到它需要一個 function 並傳遞給它 3 arguments、value、allValues 和 meta,而不僅僅是 value。 這可以幫助您編寫更好的驗證規則,以考慮有關該字段的更多信息。 無論如何,當 final-form 使用它時,它采用以下形式:
composeValidators(required)(value, allValues, meta)
我不希望這立即有意義,但它應該可以幫助您考慮一個特定的柯里化用例有一些高級選項。 享受最終形式!
https://final-form.org/docs/react-final-form/types/FieldProps
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.