Skip to content

Commit

Permalink
Add more tests for default & onChange func, updated typescript file t…
Browse files Browse the repository at this point in the history
…o show the latest changes
  • Loading branch information
amitbadala committed Oct 31, 2023
1 parent 492fee9 commit 329aee4
Show file tree
Hide file tree
Showing 3 changed files with 225 additions and 41 deletions.
84 changes: 64 additions & 20 deletions examples/for-tests/src/App.js
Original file line number Diff line number Diff line change
Expand Up @@ -177,21 +177,59 @@ const formFieldsWithDefault = [
getDefaultValue: () => "India",
},
{
id: "ratings",
label: "Ratings",
getDefaultValue: () => "best",
id: "select-dropdown",
label: "Select Option",
getDefaultValue: () => "option 2",
inputComponent: ({ value, name, onChange }) => (
<select value={value} name={name} onChange={(e) => onChange(e.target.value)} placeholder="Add Ratings">
<select value={value} name={name} onChange={(e) => onChange(e.target.value)}>
<option value="" disabled hidden>
Select an option
</option>
<option value="good">Good</option>
<option value="better">Better</option>
<option value="best">Best</option>
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3</option>
</select>
),
optional: true,
},
{
id: "terms",
label: "",
optional: false,
getDefaultValue: () => "true",
inputComponent: ({ name, onChange, value }) => (
<div
style={{
display: "flex",
alignItems: "center",
justifyContent: "left",
}}>
<input
value={value}
checked={value === "true"}
name={name}
type="checkbox"
onChange={(e) => onChange(e.target.checked.toString())}></input>
<span style={{ marginLeft: 5 }}>I agree to the terms and conditions</span>
</div>
),
validate: async (value) => {
if (value === "true") {
return undefined;
}
return "Please check Terms and conditions";
},
},
{
id: "email",
label: "Email",
getDefaultValue: () => "[email protected]",
},
{
id: "password",
label: "Password",
getDefaultValue: () => "fakepassword123",
},
];

const incorrectFormFields = [
Expand All @@ -203,22 +241,23 @@ const incorrectFormFields = [
getDefaultValue: () => 23, // return should be a string
},
{
id: "ratings",
label: "Ratings",
getDefaultValue: "best", // should be function
id: "select-dropdown",
label: "Select Dropdown",
getDefaultValue: "option 2", // should be function
inputComponent: ({ value, name, onChange }) => (
<select value={value} name={name} onChange={(e) => onChange(e.target.value)} placeholder="Add Ratings">
<select value={value} name={name} onChange={(e) => onChange(e.target.value)}>
<option value="" disabled hidden>
Select an option
</option>
<option value="good">Good</option>
<option value="better">Better</option>
<option value="best">Best</option>
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3</option>
</select>
),
optional: true,
},
{
// onChange accepts only string value, here we pass boolean
id: "terms",
label: "",
optional: false,
Expand All @@ -244,16 +283,16 @@ const incorrectFormFields = [

const customFields = [
{
id: "ratings",
label: "Ratings",
id: "select-dropdown",
label: "Select Dropdown",
inputComponent: ({ value, name, onChange }) => (
<select value={value} name={name} onChange={(e) => onChange(e.target.value)} placeholder="Add Ratings">
<select value={value} name={name} onChange={(e) => onChange(e.target.value)}>
<option value="" disabled hidden>
Select an option
</option>
<option value="good">Good</option>
<option value="better">Better</option>
<option value="best">Best</option>
<option value="option 1">Option 1</option>
<option value="option 2">Option 2</option>
<option value="option 3">Option 3</option>
</select>
),
optional: true,
Expand Down Expand Up @@ -668,6 +707,11 @@ function getEmailVerificationConfigs({ disableDefaultUI }) {

function getFormFields() {
if (localStorage.getItem("SHOW_INCORRECT_FIELDS") === "YES") {
if (localStorage.getItem("INCORRECT_ONCHANGE") === "YES") {
// since page-error blocks all the other errors
// use this filter to test specific error
return incorrectFormFields.filter(({ id }) => id === "terms");
}
return incorrectFormFields;
} else if (localStorage.getItem("SHOW_CUSTOM_FIELDS_WITH_DEFAULT_VALUES") === "YES") {
return formFieldsWithDefault;
Expand Down
176 changes: 157 additions & 19 deletions test/end-to-end/signup.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -403,20 +403,39 @@ describe("SuperTokens SignUp", function () {
assert.deepStrictEqual(formFieldErrors, ["Please check Terms and conditions"]);
});

it("Check if custom values are part of the signup payload", async function () {
it.only("Check if custom values are part of the signup payload", async function () {
const customFields = {
terms: true, // checked
ratings: "best",
terms: "true",
"select-dropdown": "option 3",
};
const requestHandler = (request) => {
let assertionError = null;
let interceptionPassed = false;
await page.setRequestInterception(true);
const requestHandler = async (request) => {
console.log("REQUEST", request.method());
if (request.url().includes(SIGN_UP_API) && request.method() === "POST") {
Object.keys(customFields).every((key) => {
assert.strictEqual(data[key], customFields[key]);
});
try {
console.log("TEdkjfhskjdfhsST", interceptionPassed);
const postData = JSON.parse(request.postData());
Object.keys(customFields).forEach((key) => {
let findFormData = postData.formFields.find((inputData) => inputData.id === key);
if (findFormData) {
assert.strictEqual(
findFormData["value"],
customFields[key],
`Mismatch in payload for key: ${key}`
);
} else {
throw new Error("Field not found in req.data");
}
});
interceptionPassed = true;
} catch (error) {
console.log("VALUER ADDED FOR ASSERTION");
assertionError = error; // Store the error
}
}
return request.continue();
};
await page.setRequestInterception(true);
page.on("request", requestHandler);

// Fill and submit the form with custom fields
Expand All @@ -426,17 +445,29 @@ describe("SuperTokens SignUp", function () {
{ name: "password", value: "Str0ngP@assw0rd" },
]);

await setSelectDropdownValue(page, 'select[name="ratings"]', customFields["ratings"]);
await setSelectDropdownValue(page, "select", customFields["select-dropdown"]);

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

// Perform the button click and wait for all network activity to finish
await submitForm(page);
await new Promise((r) => setTimeout(r, 5000));
// await page.waitForNavigation({ waitUntil: "networkidle0" });
// await page.waitForResponse();
} finally {
page.off("request", requestHandler);
await page.setRequestInterception(false);
}

if (assertionError) {
throw assertionError;
}

if (!interceptionPassed) {
throw new Error("test failed");
}
});
});

Expand All @@ -455,7 +486,8 @@ describe("SuperTokens SignUp", function () {
it("Check if default values are set already", async function () {
const fieldsWithDefault = {
country: "India",
ratings: "best",
"select-dropdown": "option 2",
terms: true,
};

// regular input field default value
Expand All @@ -464,29 +496,135 @@ describe("SuperTokens SignUp", function () {
assert.strictEqual(defaultCountry, fieldsWithDefault["country"]);

// custom dropdown default value is also getting set correctly
const ratingsDropdown = await waitForSTElement(page, "select");
const defaultRating = await ratingsDropdown.evaluate((f) => f.value);
assert.strictEqual(defaultRating, fieldsWithDefault["ratings"]);
const selectDropdown = await waitForSTElement(page, "select");
const defaultOption = await selectDropdown.evaluate((f) => f.value);
assert.strictEqual(defaultOption, fieldsWithDefault["select-dropdown"]);

// custom dropdown default value is also getting set correctly
const termsCheckbox = await waitForSTElement(page, '[name="terms"]');
// checkbox is checked
const defaultChecked = await termsCheckbox.evaluate((f) => f.checked);
assert.strictEqual(defaultChecked, fieldsWithDefault["terms"]);
// also the value = string
const defaultValue = await termsCheckbox.evaluate((f) => f.value);
assert.strictEqual(defaultValue, fieldsWithDefault["terms"].toString());
});

it("Check if changing the field value actually overwrites the default value", async function () {
const updatedFields = {
country: "USA",
ratings: "good",
"select-dropdown": "option 3",
};

await setInputValues(page, [{ name: "country", value: updatedFields["country"] }]);
await setSelectDropdownValue(page, 'select[name="ratings"]', updatedFields["ratings"]);
await setSelectDropdownValue(page, 'select[name="select-dropdown"]', updatedFields["select-dropdown"]);

// input field default value
const countryInput = await getInputField(page, "country");
const updatedCountry = await countryInput.evaluate((f) => f.value);
assert.strictEqual(updatedCountry, updatedFields["country"]);

// dropdown default value is also getting set correctly
const ratingsDropdown = await waitForSTElement(page, "select");
const updatedRating = await ratingsDropdown.evaluate((f) => f.value);
assert.strictEqual(updatedRating, updatedFields["ratings"]);
const selectDropdown = await waitForSTElement(page, "select");
const updatedOption = await selectDropdown.evaluate((f) => f.value);
assert.strictEqual(updatedOption, updatedFields["select-dropdown"]);
});

it("Check if default values are getting sent in signup-payload", async function () {
// directly submit the form and test the payload
const expectedDefautlValues = [
{ id: "email", value: "[email protected]" },
{ id: "password", value: "[email protected]" },
{ id: "terms", value: "true" },
{ id: "select-dropdown", value: "option 2" },
{ id: "country", value: "India" },
];

let assertionError = null;
const requestHandler = async (request) => {
if (request.url().includes(SIGN_UP_API) && request.method() === "POST") {
try {
const postData = JSON.parse(request.postData());
Object.keys(customFields).forEach((key) => {
let findFormData = postData.formFields.find((inputData) => inputData.id === key);
if (findFormData) {
assert.strictEqual(
findFormData["value"],
customFields[key],
`Mismatch in payload for key: ${key}`
);
} else {
assert.fail("Field not found in req.data");
}
});
} catch (error) {
console.log("VALUER ADDED FOR ASSERTION");
assertionError = error; // Store the error
}
}
return request.continue();
};
await page.setRequestInterception(true);
page.on("request", requestHandler);

await submitForm(page);
await new Promise((resolve) => setTimeout(resolve, 3000));

if (assertionError) {
throw assertionError;
}
});
});

describe("Incorrect field config test", function () {
beforeEach(async function () {
// set cookie and reload which loads the form fields with default values
await page.evaluate(() => window.localStorage.setItem("SHOW_INCORRECT_FIELDS", "YES"));

await page.reload({
waitUntil: "domcontentloaded",
});
});

it("Check if incorrect getDefaultValue throws error", async function () {
let pageErrorMessage = "";
page.on("pageerror", (err) => {
pageErrorMessage = err.message;
});

await page.reload({
waitUntil: "domcontentloaded",
});
await toggleSignInSignUp(page);

const expectedErrorMessage = "getDefaultValue for country must return a string";
assert(
pageErrorMessage.includes(expectedErrorMessage),
`Expected "${expectedErrorMessage}" to be included in page-error`
);
});

it("Check if non-string params to onChange throws error", async function () {
await page.evaluate(() => window.localStorage.setItem("INCORRECT_ONCHANGE", "YES"));
await page.reload({
waitUntil: "domcontentloaded",
});
await toggleSignInSignUp(page);

let pageErrorMessage = "";
page.on("pageerror", (err) => {
pageErrorMessage = err.message;
});

// check terms and condition checkbox since it emits non-string value => boolean
let termsCheckbox = await waitForSTElement(page, '[name="terms"]');
await page.evaluate((e) => e.click(), termsCheckbox);

const expectedErrorMessage = "terms value must be a string";
assert(
pageErrorMessage.includes(expectedErrorMessage),
`Expected "${expectedErrorMessage}" to be included in page-error`
);
});

// TODO
Expand Down
6 changes: 4 additions & 2 deletions test/with-typescript/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -377,6 +377,7 @@ function getEmailPasswordConfigs() {
id: "terms",
label: "",
optional: false,
getDefaultValue: () => "true",
inputComponent: (inputProps) => (
<div
style={{
Expand All @@ -387,6 +388,8 @@ function getEmailPasswordConfigs() {
<input
name={inputProps.name}
type="checkbox"
value={inputProps.value}
checked={inputProps.value === "true"}
onChange={(e) => {
if (inputProps.onChange) {
inputProps.onChange(e.target.checked.toString());
Expand Down Expand Up @@ -424,8 +427,7 @@ function getEmailPasswordConfigs() {
if (inputProps.onChange) {
inputProps.onChange(e.target.value);
}
}}
placeholder="Select option">
}}>
<option value="" disabled hidden>
Select an option
</option>
Expand Down

0 comments on commit 329aee4

Please sign in to comment.