Merge pull request #1215 from Safelite/customer-details-unit-tests

Customer details unit tests
This commit is contained in:
Leah Schumann 2023-07-10 10:47:10 -04:00 committed by GitHub
commit 97f19af041
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 301 additions and 159 deletions

View file

@ -0,0 +1,64 @@
// Components
import phoneNumberQuestion from "./phone-number-question";
// Supporting Files
import { shallowMount } from "@vue/test-utils";
describe("phone-number-question.vue", () => {
it("Should render phoneNumberQuestion sub-component (textbox-question)", async () => {
// Arrange
const wrapper = shallowMount(phoneNumberQuestion, {});
wrapper.getCmsContent = jest.fn();
// Act
const phoneNumber = wrapper.findComponent({ ref: "phoneNumber" });
// Assert
expect(phoneNumber.exists()).toBe(true);
});
it("Should emit new value when modelValue is changed", async () => {
// Act
const wrapper = shallowMount(phoneNumberQuestion, {
propsData: {
modelValue: "val",
},
});
const phoneNumber = wrapper.findComponent({ ref: "phoneNumber" });
await phoneNumber.setValue("val2");
// Assert
expect(wrapper.emitted("update:modelValue")).toEqual([["val2"]]);
});
it("Should emit new value when modelValue is changed", async () => {
// Act
const wrapper = shallowMount(phoneNumberQuestion, {
propsData: {
modelValue: "val",
},
});
const phoneNumber = wrapper.findComponent({ ref: "phoneNumber" });
await phoneNumber.setValue("val2");
// Assert
expect(wrapper.emitted("update:modelValue")).toEqual([["val2"]]);
});
it("Should combine external and internal validation rules to pass to textbox-question", async () => {
// Act
const wrapper = shallowMount(phoneNumberQuestion, {
propsData: {
validationRules: "outsideValidation",
},
});
// Assert
expect(wrapper.vm.validationRulesForTextBoxQuestion).toEqual(
"outsideValidation|phone-number-format"
);
});
});

View file

@ -0,0 +1,95 @@
<template>
<div class="phone-number-question d-flex flex-column">
<textboxQuestion
ref="phoneNumber"
type="text"
:max-length="12"
v-model="selectedValue"
:mask="mask"
:isRequired="isRequired"
:validationRules="validationRulesForTextBoxQuestion"
cmsWidgetName="PhoneNumberQuestionWidget" />
</div>
</template>
<script>
import textboxQuestion from "@/digital-components/textbox-question/textbox-question";
// Supporting files
import { errorMessages } from "@/constants/error-messages";
import { regex } from "@/helpers/validation-rules";
import { defineRule } from "vee-validate";
// Validation
defineRule(
"phone-number-format",
regex(/^(?=(?:.*\d){10})(?=(?:.*-){2})[\d-]{12}$/, errorMessages.PHONE_FORMAT)
);
export default {
name: "phoneNumberQuestion",
props: {
cmsWidgetName: String,
isRequired: Boolean,
validationRules: String,
hasError: Boolean,
centerErrorMessage: Boolean,
modelValue: String,
},
data() {
return {
phoneNumber: "",
};
},
computed: {
selectedValue: {
get: function () {
return this.modelValue;
},
set: function (newValue) {
this.$emit("update:modelValue", newValue);
},
},
validationRulesForTextBoxQuestion() {
if (!this.validationRules || this.validationRules.length === 0) {
return "phone-number-format";
} else {
return this.validationRules + "|phone-number-format";
}
},
mask() {
return {
mask: "x##-###-####",
tokens: {
x: {
pattern: /[2-9]/,
},
},
};
},
},
components: {
textboxQuestion,
},
};
</script>
<style lang="scss">
.phone-number-question {
label {
color: $black;
}
input {
border-radius: 0.5rem;
border: 1px solid $gray-500;
height: 48px;
&:focus {
box-shadow: 0 0 0 2.5px $blue;
outline: none;
}
&:hover {
box-shadow: 0 0 0 4px $blue-300;
}
}
}
</style>

View file

@ -1 +0,0 @@
test.todo("some test to be written in the future");

View file

@ -1,119 +0,0 @@
<template>
<div class="phonenumber-question d-flex flex-column">
<textboxQuestion
type="text"
:max-length="12"
v-model="selectedValue"
:isRequired="isRequired"
:validationRules="validationRuleForTextBoxQuestion"
@input="filterNumber"
cmsWidgetName="phoneNumberQuestionWidget" />
</div>
</template>
<script>
import textboxQuestion from "@/digital-components/textbox-question/textbox-question";
//Supporting files
import { errorMessages } from "@/constants/error-messages";
import { required, regex } from "@/helpers/validation-rules";
import { Form, defineRule } from "vee-validate";
import { useField, validate } from "vee-validate";
//Validation
defineRule(
"phone-number-format",
regex(/^(?=(?:.*\d){10})(?=(?:.*-){2})[\d-]{12}$/, errorMessages.PHONE_FORMAT)
);
export default {
name: "phoneNumberQuestion",
props: {
cmsWidgetName: String,
isRequired: Boolean,
validationRules: String,
hasError: Boolean,
centerErrorMessage: Boolean,
modelValue: String,
},
data() {
return {
phoneNumber: "",
};
},
computed: {
phoneNumberQuestionWidget() {
return this.getCmsContent(this.cmsWidgetName, "QuestionText");
},
selectedValue: {
get: function () {
return this.modelValue;
},
set: function (newValue) {
const formattedNumber = this.formatPhoneNumber(newValue);
this.$emit("update:modelValue", formattedNumber);
},
},
validationRuleForTextBoxQuestion() {
if (!this.validationRules || this.validationRules.length === 0) {
return "phone-number-format";
} else {
return this.validationRules + "|phone-number-format";
}
},
},
methods: {
formatPhoneNumber(value) {
// Remove all non-digit characters from the phone number
let formattedNumber = value.replace(/\D/g, "");
// Insert hyphens after the first three and the next three digits
if (formattedNumber.length > 3) {
formattedNumber = formattedNumber.slice(0, 3) + "-" + formattedNumber.slice(3);
}
if (formattedNumber.length > 7) {
formattedNumber = formattedNumber.slice(0, 7) + "-" + formattedNumber.slice(7);
}
// Update the phone number with the formatted version
return formattedNumber;
},
filterNumber(event) {
const regex = /^(?!1)\d+/;
const inputValue = event.target.value;
if (!regex.test(inputValue)) {
// If the input violates the regex pattern, remove the leading 1
event.target.value = inputValue.replace(/^1/, "");
}
},
},
watch: {
async value(newValue) {
const result = await validate(newValue, this.validationRules); // do a test validation check, without triggering full validation
if (result.valid) {
this.handleChange(newValue); // trigger full validation on this field only
}
},
},
components: {
textboxQuestion,
},
};
</script>
<style lang="scss">
.phonenumber-question {
label {
color: $black;
}
input {
border-radius: 0.5rem;
border: 1px solid $gray-500;
height: 48px;
&:focus {
box-shadow: 0 0 0 2.5px $blue;
outline: none;
}
&:hover {
box-shadow: 0 0 0 4px $blue-300;
}
}
}
</style>

View file

@ -1 +1,61 @@
test.todo("some test to be written in the future");
// Components
import textareaQuestion from "./textarea-question";
// Supporting Files
import { shallowMount } from "@vue/test-utils";
const maska = jest.fn();
const questionText = "textareaQuestionText";
const mockMixin = {
methods: {
getCmsContent: jest.fn().mockImplementation(() => {
return questionText;
}),
},
};
describe("textarea-question.vue", () => {
it("Should render a textarea", async () => {
// Arrange
const wrapper = shallowMount(textareaQuestion, {
global: {
directives: {
maska: maska,
},
},
propsData: {
modelValue: "",
},
mixins: [mockMixin],
});
wrapper.getCmsContent = jest.fn();
// Act
const textarea = wrapper.find("textarea");
// Assert
expect(textarea.exists()).toBe(true);
});
it("Should emit new value when modelValue is changed", async () => {
// Act
const wrapper = shallowMount(textareaQuestion, {
global: {
directives: {
maska: maska,
},
},
propsData: {
modelValue: "val",
},
mixins: [mockMixin],
});
await wrapper.find("textarea").setValue("val2");
// Assert
expect(wrapper.emitted("update:modelValue")).toEqual([["val2"]]);
});
});

View file

@ -1,14 +1,16 @@
<template>
<div class="textarea-question">
<div class="label-wrapper mb-1" :aria-label="TextAreaContentWidget">
<div class="label-wrapper mb-1" :aria-label="questionText">
<!-- Wrap label and span because v-html prevents v-if from displaying if v-if <span> is inside <label>-->
<label for="textarea-comments" class="fw-bold" v-html="TextAreaContentWidget"></label>
<label for="textarea-question" class="fw-bold" v-html="questionText"></label>
<span v-if="!isRequired" class="fw-normal ms-1">(Optional)</span>
</div>
<textarea
id="textareaQuestion"
ref="textarea"
v-model="value"
v-maska="mask"
@keyup="updateCount"
id="textarea-comments"
class="p-4"
:maxlength="maxLength"
role="textbox"
@ -18,7 +20,7 @@
<p
tabindex="0"
class="caption mt-2 mb-0"
id="charactersremaining"
id="charactersRemaining"
:class="[urgentCountdown ? 'urgent-countdown' : '']">
{{ remainingCount }}/{{ maxLength }} characters remaining
</p>
@ -37,30 +39,10 @@ export default {
},
modelValue: String,
},
setup(props) {
const inputId = !props.customInputId ? `input-${crypto.randomUUID()}` : props.customInputId;
const propsClone = Object.assign({}, props);
const modelValue = propsClone.modelValue;
let initialValue;
switch (typeof modelValue) {
case "number":
initialValue = modelValue;
break;
default:
initialValue = modelValue && modelValue.length > 0 ? modelValue : "";
break;
}
const fieldOptions = {
type: "text",
value: modelValue,
initialValue: initialValue,
};
},
// TODO: At some point in the future we should probably add the tie in to validation here in case the field must be populated for some other use cases
setup() {},
computed: {
TextAreaContentWidget() {
questionText() {
return this.getCmsContent(this.cmsWidgetName, "QuestionText");
},
value: {
@ -77,12 +59,16 @@ export default {
urgentCountdown() {
return this.remainingCount <= this.maxLength * 0.1 ? true : false;
},
},
methods: {
updateCount() {
if (this.value.length > this.maxLength) {
this.value = this.value.slice(0, this.maxLength);
}
mask() {
// Allow any character but only the max length number of times.
return {
mask: `x*${this.maxLength}`,
tokens: {
x: {
pattern: /.|\n|\r/,
},
},
};
},
},
};

View file

@ -1 +1,58 @@
test.todo("some test to be written in the future");
// Components
import customerDetails from "@/layouts/customer-details/customer-details.vue";
// Supporting Files
import { shallowMount } from "@vue/test-utils";
import { getMountOptions } from "@/helpers/unit-test-helper.js";
import * as navigateToHeritage from "@/helpers/heritage-integration/navigation-helper";
jest.mock("@/helpers/heritage-integration/navigation-helper", () => ({
navigateToHeritageFunnel: jest.fn(),
}));
// Mock our module for promises.
jest.mock("@/helpers/layout-helper.js", () => ({
settleAllPromises: jest.fn(),
}));
describe("customer-details.vue", () => {
describe("navigation", () => {
test("if the back button is clicked, navigate back", async () => {
// Arrange
const { wrapper } = setupMocks();
// Act
await wrapper.vm.backButtonAction();
// Assert
expect(wrapper.vm.$router.navigateWithoutSaving).toHaveBeenCalled();
});
test("if the continue button is clicked, navigate forward", async () => {
// Arrange
const { wrapper } = setupMocks();
// Act
await wrapper.vm.forwardButtonAction();
// Assert
expect(navigateToHeritage.navigateToHeritageFunnel).toHaveBeenCalled();
});
});
});
function setupMocks() {
const wrapper = shallowMount(
customerDetails,
getMountOptions({
router: {
navigate: jest.fn(),
navigate: jest.fn(),
navigateWithSaving: jest.fn(),
navigateWithoutSaving: jest.fn(),
},
})
);
return { wrapper };
}

View file

@ -8,14 +8,14 @@
cmsWidgetName="FirstNameWidget"
v-model="firstName"
ref="firstName"
inputId="08497a2efd9a4a73a70360ab47b4838d"
customInputId="firstName"
validationRules="first-name-required" />
<textboxQuestion
class="mb-4"
cmsWidgetName="LastNameWidget"
v-model="lastName"
ref="lastName"
inputId="0030e56a57e74a4ab92de7fb8e97fec5"
customInputId="lastName"
validationRules="last-name-required" />
<textboxQuestion
class="mb-4"
@ -55,7 +55,7 @@ import funnelFooter from "@/fmg-components/funnel-footer/funnel-footer";
import funnelSubHeader from "@/fmg-components/funnel-sub-header/funnel-sub-header";
import textareaQuestion from "@/digital-components/textarea-question/textarea-question";
import textboxQuestion from "@/digital-components/textbox-question/textbox-question";
import phoneNumberQuestion from "@/digital-components/phonenumber-question/phonenumber-question";
import phoneNumberQuestion from "@/digital-components/phone-number-question/phone-number-question";
import textBlock from "@/digital-components/text-block/text-block";
import checkboxQuestion from "@/digital-components/checkbox-question/checkbox-question";
//Supporting files

View file

@ -103,7 +103,7 @@ html {
}
&.textbox-question,
&.dropdown-question,
&.phonenumber-question {
&.phone-number-question {
p {
color: $red;
}