diff --git a/src/utils.js b/src/utils.js index 8c69cccae8..ad92ee494b 100644 --- a/src/utils.js +++ b/src/utils.js @@ -67,6 +67,11 @@ export function getDefaultRegistry() { export function getSchemaType(schema) { let { type } = schema; + + if (!type && schema.const) { + return guessType(schema.const); + } + if (!type && schema.enum) { type = "string"; } diff --git a/test/const_test.js b/test/const_test.js new file mode 100644 index 0000000000..d47e012bd2 --- /dev/null +++ b/test/const_test.js @@ -0,0 +1,60 @@ +import { expect } from "chai"; + +import { createFormComponent, createSandbox } from "./test_utils"; + +describe("const", () => { + let sandbox; + + beforeEach(() => { + sandbox = createSandbox(); + }); + + afterEach(() => { + sandbox.restore(); + }); + + it("should render a schema that uses const with a string value", () => { + const schema = { + type: "object", + properties: { + foo: { const: "bar" }, + }, + }; + + const { node } = createFormComponent({ + schema, + }); + + expect(node.querySelector("input#root_foo")).not.eql(null); + }); + + it("should render a schema that uses const with a number value", () => { + const schema = { + type: "object", + properties: { + foo: { const: 123 }, + }, + }; + + const { node } = createFormComponent({ + schema, + }); + + expect(node.querySelector("input#root_foo")).not.eql(null); + }); + + it("should render a schema that uses const with a boolean value", () => { + const schema = { + type: "object", + properties: { + foo: { const: true }, + }, + }; + + const { node } = createFormComponent({ + schema, + }); + + expect(node.querySelector("input#root_foo[type='checkbox']")).not.eql(null); + }); +}); diff --git a/test/utils_test.js b/test/utils_test.js index 7ba1be7601..cb32727c06 100644 --- a/test/utils_test.js +++ b/test/utils_test.js @@ -5,6 +5,7 @@ import { dataURItoBlob, deepEquals, getDefaultFormState, + getSchemaType, isFilesArray, isConstant, toConstant, @@ -1369,4 +1370,51 @@ describe("utils", () => { expect(guessType({})).eql("object"); }); }); + + describe("getSchemaType()", () => { + const cases = [ + { + schema: { type: "string" }, + expected: "string", + }, + { + schema: { type: "number" }, + expected: "number", + }, + { + schema: { type: "integer" }, + expected: "integer", + }, + { + schema: { type: "object" }, + expected: "object", + }, + { + schema: { type: "array" }, + expected: "array", + }, + { + schema: { type: "boolean" }, + expected: "boolean", + }, + { + schema: { type: "null" }, + expected: "null", + }, + { + schema: { const: "foo" }, + expected: "string", + }, + { + schema: { const: 1 }, + expected: "number", + }, + ]; + + it("should correctly guess the type of a schema", () => { + for (const test of cases) { + expect(getSchemaType(test.schema)).eql(test.expected); + } + }); + }); });