Skip to content

Commit

Permalink
Add tests for custom fields
Browse files Browse the repository at this point in the history
  • Loading branch information
amitbadala committed Oct 23, 2023
1 parent e2b95de commit 52e7dab
Show file tree
Hide file tree
Showing 5 changed files with 191 additions and 1 deletion.
49 changes: 48 additions & 1 deletion examples/for-tests/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,52 @@ const formFields = [
},
];

const customFields = [
{
id: "ratings",
label: "Ratings",
inputComponent: ({ value, name, ...rest }) => (
<select
name={name}
data-supertokens="inputComponent"
placeholder="Add Ratings"
onChange={(e) => rest.onChange({ id: name, value: e.target.value })}>
<option value="" disabled hidden>
Select an option
</option>
<option value={1}>1</option>
<option value={2}>2</option>
<option value={3}>3</option>
</select>
),
optional: true,
},
{
id: "terms",
showLabels: false,
optional: false,
inputComponent: ({ value, name, ...rest }) => (
<div
data-supertokens="inputComponent"
style={{
display: "flex",
alignItems: "center",
justifyContent: "left",
}}>
<input
name={name}
type="checkbox"
onChange={(e) => rest.onChange({ id: name, value: e.target.checked })}></input>
<span style={{ marginLeft: 5 }}>I agree to the terms and conditions</span>
</div>
),
validate: async (value) => {
if (value) return undefined;
return "Please check Terms and conditions";
},
},
];

const testContext = getTestContext();

let recipeList = [
Expand Down Expand Up @@ -637,7 +683,8 @@ function getEmailPasswordConfigs({ disableDefaultUI }) {
style: theme,
privacyPolicyLink: "https://supertokens.com/legal/privacy-policy",
termsOfServiceLink: "https://supertokens.com/legal/terms-and-conditions",
formFields,
formFields:
localStorage.getItem("SHOW_CUSTOM_FIELDS") === "YES" ? formFields.concat(customFields) : formFields,
},
},
});
Expand Down
1 change: 1 addition & 0 deletions lib/build/types.d.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions lib/ts/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,11 @@ export type NormalisedFormField = {
* Moves focus to the input element when it mounts
*/
autofocus?: boolean;

/*
* Ability to add custom components
*/
inputComponent?: React.FC<InputProps>;
};

export type ReactComponentClass<P = any> = ComponentClass<P, any> | ((props: P) => JSX.Element);
Expand Down
132 changes: 132 additions & 0 deletions test/end-to-end/signup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import {
getGeneralError,
waitForSTElement,
backendBeforeEach,
getCustomComponents,
} from "../helpers";

import {
Expand Down Expand Up @@ -414,3 +415,134 @@ describe("SuperTokens SignUp => Server Error", function () {
await waitForSTElement(page, "[data-supertokens~=generalError]", true);
});
});

// CUSTOM FIELDS TEST

describe("Signup custom fields test", function () {
let browser;
let page;
let consoleLogs;

before(async function () {
await backendBeforeEach();

await fetch(`${TEST_SERVER_BASE_URL}/startst`, {
method: "POST",
}).catch(console.error);

browser = await puppeteer.launch({
args: ["--no-sandbox", "--disable-setuid-sandbox"],
headless: false,
});
page = await browser.newPage();
});

// after(async function () {
// await browser.close();
// });

afterEach(function () {
return screenshotOnFailure(this, browser);
});

beforeEach(async function () {
consoleLogs = [];
consoleLogs = await clearBrowserCookiesWithoutAffectingConsole(page, consoleLogs);
await Promise.all([
page.goto(`${TEST_CLIENT_BASE_URL}`),
page.waitForNavigation({ waitUntil: "networkidle0" }),
]);

await page.evaluate(() => window.localStorage.setItem("SHOW_CUSTOM_FIELDS", "YES"));

let elem = await getLoginWithRedirectToSignUp(page);
await page.evaluate((e) => e.click(), elem);
await page.waitForNavigation({ waitUntil: "networkidle0" });
});

it("Check if the custom fields are loaded", async function () {
let text = await getAuthPageHeaderText(page);
assert.deepStrictEqual(text, "Sign Up");

// check if select dropdown is loaded
const selectDropdownExists = await getCustomComponents(page, "select");
assert.ok(selectDropdownExists, "Select dropdown exists");

// check if checbox is loaded
const checkboxExists = await getCustomComponents(page, 'input[type="checkbox"]');
assert.ok(checkboxExists, "Checkbox exists");
});

it("Should show error messages, based on the validation", async function () {
await submitForm(page);
let formFieldErrors = await getFieldErrors(page);

// 4 regular form field errors +
// 1 required custom field => terms checkbox
assert.deepStrictEqual(formFieldErrors, [
"Field is not optional",
"Field is not optional",
"Field is not optional",
"Field is not optional",
"Field is not optional",
]);

// supply values for regular-required fields only
await setInputValues(page, [
{ name: "email", value: "[email protected]" },
{ name: "password", value: "Str0ngP@ssw0rd" },
{ name: "name", value: "John Doe" },
{ name: "age", value: "20" },
]);
await submitForm(page);
formFieldErrors = await getFieldErrors(page);
assert.deepStrictEqual(formFieldErrors, ["Field is not optional"]);

// check terms and condition checkbox
let termsCheckbox = await getCustomComponents(page, '[name="terms"]');
await page.evaluate((e) => e.click(), termsCheckbox);
await submitForm(page);
formFieldErrors = await getFieldErrors(page);
assert.deepStrictEqual(formFieldErrors, []);
});

it.only("Check if custom values are part of the signup payload", async function () {
const customFieldNames = ["terms", "ratings"];
const requestHandler = (request) => {
if (request.url().includes(SIGN_UP_API) && request.method() === "POST") {
assert.ok(
customFieldNames.every((key) => request.data.hasOwnProperty(key)),
"Custom field are part of the payload"
);
}
return request.continue();
};

try {
await page.setRequestInterception(true);
page.on("request", requestHandler);

// Fill the entire form
await setInputValues(page, [
{ name: "email", value: "[email protected]" },
{ name: "password", value: "Str0ngP@assw0rd" },
{ name: "name", value: "Supertokens" },
{ name: "age", value: "20" },
]);

// Select value from dropdown (ratings)
let dropdownEle = await getCustomComponents(page, '[name="ratings"]');
const dropdownValue = 3;
await page.select(dropdownEle, dropdownValue);

// Check terms and condition checkbox
let termsCheckbox = await getCustomComponents(page, '[name="terms"]');
await page.evaluate((e) => e.click(), termsCheckbox);

await submitForm(page);
} finally {
page.off("request", requestHandler);
await page.setRequestInterception(false);
}
});
});
5 changes: 5 additions & 0 deletions test/helpers.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
import path from "path";
import assert from "assert";
import mkdirp from "mkdirp";
import { async } from "regenerator-runtime";

const SESSION_STORAGE_STATE_KEY = "supertokens-oauth-state";

Expand Down Expand Up @@ -233,6 +234,10 @@ export async function getInputNames(page) {
);
}

export async function getCustomComponents(page, element) {
return waitForSTElement(page, element);
}

export async function getInputAdornmentsSuccess(page) {
await waitForSTElement(page);
return await page.evaluate(
Expand Down

0 comments on commit 52e7dab

Please sign in to comment.