import { assert } from "chai" import React from "react" import moment from "moment" import { render, cleanup } from "@testing-library/react" import { Schema } from "@mwater/expressions" import FormComponent from "../src/FormComponent" import { FormDesign } from "../src/formDesign" import { ResponseData } from "../src/response" describe("FormComponent onDataInitialized", function () { afterEach(function () { cleanup() }) const design: FormDesign = { _type: "Form", _schema: 1, name: { _base: "en", en: "Test Form" }, locales: [{ code: "en", name: "English" }], contents: [ { _id: "visitdate", _type: "DateQuestion", text: { _base: "en", en: "Visit date" }, format: "YYYY-MM-DD", defaultNow: true, conditions: [], validations: [] } as any, { _id: "notes", _type: "TextQuestion", text: { _base: "en", en: "Notes" }, format: "singleline", conditions: [], validations: [] } as any ], calculations: [] } // Defaults are only applied when the context has sticky storage const formCtx: any = { stickyStorage: { get: () => undefined, set: () => undefined }, getEntityById: (entityType: string, entityId: string, callback: (entity: any) => void) => callback(null), getEntityByCode: (entityType: string, entityCode: string, callback: (entity: any) => void) => callback(null), getCustomTableRow: async () => null, getAssetById: async () => null } /** Waits until the condition holds. The asynchronous response cleaning has no DOM to wait on */ async function waitUntil(condition: () => boolean) { for (let i = 0; i < 100 && !condition(); i++) { await new Promise((resolve) => setTimeout(resolve, 10)) } assert.isTrue(condition(), "Timed out waiting") } function renderForm(data: ResponseData, onDataChange: (data: ResponseData) => void, onDataInitialized: (data: ResponseData) => void) { return render( ) } it("reports the mount-time data once defaults have been applied", async function () { const changes: ResponseData[] = [] const initialized: ResponseData[] = [] renderForm({}, (data) => changes.push(data), (data) => initialized.push(data)) await waitUntil(() => initialized.length > 0) // Defaults applied, and the same data as the last change reported during mounting assert.equal((initialized[0].visitdate as any)?.value, moment().format("YYYY-MM-DD")) assert.deepEqual(changes[changes.length - 1], initialized[0]) // The raw data was reported before the defaults, which is why it cannot be the baseline assert.deepEqual(changes[0], {}) }) it("reports only once, not for later changes", async function () { const initialized: ResponseData[] = [] const { rerender } = renderForm({}, () => null, (data) => initialized.push(data)) await waitUntil(() => initialized.length > 0) // External change to the data rerender( null} onDataInitialized={(data) => initialized.push(data)} /> ) await new Promise((resolve) => setTimeout(resolve, 50)) assert.lengthOf(initialized, 1) }) })