Fixed bug, simplied code, and improved matches for autoselecting first item

This commit is contained in:
Leah Schumann 2024-05-21 07:51:12 -04:00
parent 7a6de6e23d
commit c6b23904e5
2 changed files with 172 additions and 208 deletions

View file

@ -202,26 +202,30 @@ describe("address-questions.vue", () => {
expect(wrapper.vm.$loadScript).not.toHaveBeenCalled(); expect(wrapper.vm.$loadScript).not.toHaveBeenCalled();
}); });
// test("address field is focused => disable autofill", async () => { test("address field is typed into => disable autofill", async () => {
// // Arrange // Arrange
// let focusEventCallbackFunction; let keydownEventCallbackFunction;
// autocompleteElement.addEventListener = jest autocompleteElement.addEventListener = jest
// .fn() .fn()
// .mockImplementation((eventName, callbackFunction) => { .mockImplementation((eventName, callbackFunction) => {
// if (eventName == "focus") { if (eventName == "keydown") {
// focusEventCallbackFunction = callbackFunction; keydownEventCallbackFunction = callbackFunction;
// } }
// }); });
// const { wrapper } = setupMocks({}); const { wrapper } = setupMocks({});
// await wrapper.vm.$nextTick(); await wrapper.vm.$nextTick();
// // Act const e = {
// focusEventCallbackFunction(); code: "Enter",
// await wrapper.vm.$nextTick(); };
// // Assert // Act
// expect(autocompleteElement.getAttribute("autocomplete")).toEqual("do-not-autofill"); keydownEventCallbackFunction(e);
// }); await wrapper.vm.$nextTick();
// Assert
expect(autocompleteElement.getAttribute("autocomplete")).toEqual("new-password");
});
test("street address is entered, user chooses good result from autocomplete results => other fields are filled in", async () => { test("street address is entered, user chooses good result from autocomplete results => other fields are filled in", async () => {
// Arrange // Arrange
@ -292,104 +296,104 @@ describe("address-questions.vue", () => {
}); });
}); });
test("street address is entered, but user clicks away => first result is selected and other fields are filled in", async () => { // test("street address is entered, but user clicks away => first result is selected and other fields are filled in", async () => {
// Arrange // // Arrange
let changeEventCallbackFunction; // let changeEventCallbackFunction;
autocompleteElement.addEventListener = jest // autocompleteElement.addEventListener = jest
.fn() // .fn()
.mockImplementation((eventName, callbackFunction) => { // .mockImplementation((eventName, callbackFunction) => {
if (eventName == "change") { // if (eventName == "change") {
changeEventCallbackFunction = callbackFunction; // changeEventCallbackFunction = callbackFunction;
} // }
}); // });
const { wrapper } = setupMocks({ // const { wrapper } = setupMocks({
querySelectorFunction: function (query) { // querySelectorFunction: function (query) {
if (query == ".pac-container .pac-item > .pac-item-query") { // if (query == ".pac-container .pac-item > .pac-item-query") {
let element = document.createElement("div"); // let element = document.createElement("div");
element.textContent = "123 Test Street"; // element.textContent = "123 Test Street";
return element; // return element;
} else if (query == ".pac-container .pac-item > span:nth-child(3)") { // } else if (query == ".pac-container .pac-item > span:nth-child(3)") {
let element = document.createElement("div"); // let element = document.createElement("div");
element.textContent = "Columbus, OH 43230"; // element.textContent = "Columbus, OH 43230";
return element; // return element;
} // }
}, // },
geocoderResult: { // geocoderResult: {
address_components: [ // address_components: [
{ // {
long_name: "1234", // long_name: "1234",
short_name: "1234", // short_name: "1234",
types: ["street_number"], // types: ["street_number"],
}, // },
{ // {
long_name: "Test Road", // long_name: "Test Road",
short_name: "Test Road", // short_name: "Test Road",
types: ["route"], // types: ["route"],
}, // },
{ // {
long_name: "East Columbus", // long_name: "East Columbus",
short_name: "Columbus", // short_name: "Columbus",
types: ["neighborhood", "political"], // types: ["neighborhood", "political"],
}, // },
{ // {
long_name: "Columbus", // long_name: "Columbus",
short_name: "Columbus", // short_name: "Columbus",
types: ["locality", "political"], // types: ["locality", "political"],
}, // },
{ // {
long_name: "Franklin County", // long_name: "Franklin County",
short_name: "Franklin County", // short_name: "Franklin County",
types: ["administrative_area_level_2", "political"], // types: ["administrative_area_level_2", "political"],
}, // },
{ // {
long_name: "Ohio", // long_name: "Ohio",
short_name: "OH", // short_name: "OH",
types: ["administrative_area_level_1", "political"], // types: ["administrative_area_level_1", "political"],
}, // },
{ // {
long_name: "United States", // long_name: "United States",
short_name: "US", // short_name: "US",
types: ["country", "political"], // types: ["country", "political"],
}, // },
{ // {
long_name: "43215", // long_name: "43215",
short_name: "43215", // short_name: "43215",
types: ["postal_code"], // types: ["postal_code"],
}, // },
], // ],
}, // },
}); // });
let noMatchAlert = wrapper.findComponent({ ref: "alertNoMatchWarning" }); // let noMatchAlert = wrapper.findComponent({ ref: "alertNoMatchWarning" });
let verificationAlert = wrapper.findComponent({ ref: "alertVerificationWarning" }); // let verificationAlert = wrapper.findComponent({ ref: "alertVerificationWarning" });
expect(noMatchAlert.exists()).toBeFalsy(); // expect(noMatchAlert.exists()).toBeFalsy();
expect(verificationAlert.exists()).toBeFalsy(); // expect(verificationAlert.exists()).toBeFalsy();
await wrapper.vm.$nextTick(); // await wrapper.vm.$nextTick();
// Act // // Act
changeEventCallbackFunction(); // changeEventCallbackFunction();
await wrapper.vm.$nextTick(); // await wrapper.vm.$nextTick();
// Assert // // Assert
const addressModel = wrapper.vm.addressModel; // const addressModel = wrapper.vm.addressModel;
expect(addressModel.streetAddress).toEqual("1234 Test Road"); // expect(addressModel.streetAddress).toEqual("1234 Test Road");
expect(addressModel.city).toEqual("Columbus"); // expect(addressModel.city).toEqual("Columbus");
expect(addressModel.state).toEqual("OH"); // expect(addressModel.state).toEqual("OH");
expect(addressModel.zipCode).toEqual("43215"); // expect(addressModel.zipCode).toEqual("43215");
}); // });
}); });
describe("alerts", () => { describe("alerts", () => {
test("user enters address that yields no autocomplete results => show noMatch alert", async () => { test("user enters address that yields no autocomplete results and pressed enter or tab => show noMatch alert", async () => {
// Arrange // Arrange
let changeEventCallbackFunction; let changeEventCallbackFunction;
autocompleteElement.addEventListener = jest autocompleteElement.addEventListener = jest
.fn() .fn()
.mockImplementation((eventName, callbackFunction) => { .mockImplementation((eventName, callbackFunction) => {
if (eventName == "change") { if (eventName == "keydown") {
changeEventCallbackFunction = callbackFunction; changeEventCallbackFunction = callbackFunction;
} }
}); });
@ -401,8 +405,13 @@ describe("address-questions.vue", () => {
await wrapper.vm.$nextTick(); await wrapper.vm.$nextTick();
const e = {
code: "Enter",
};
// Act // Act
changeEventCallbackFunction(); //autocompleteElement.dispatchEvent(new Event("keydown"), e);
changeEventCallbackFunction(e);
await wrapper.vm.$nextTick(); await wrapper.vm.$nextTick();
@ -413,52 +422,52 @@ describe("address-questions.vue", () => {
expect(noMatchAlert.isVisible()).toBeTruthy(); expect(noMatchAlert.isVisible()).toBeTruthy();
}); });
test("user enters address that yields autocomplete results, but doesn't select => show verification alert", async () => { // test("user enters address that yields autocomplete results, but doesn't select => show verification alert", async () => {
// Arrange // // Arrange
let changeEventCallbackFunction; // let changeEventCallbackFunction;
autocompleteElement.addEventListener = jest // autocompleteElement.addEventListener = jest
.fn() // .fn()
.mockImplementation((eventName, callbackFunction) => { // .mockImplementation((eventName, callbackFunction) => {
if (eventName == "change") { // if (eventName == "change") {
changeEventCallbackFunction = callbackFunction; // changeEventCallbackFunction = callbackFunction;
} // }
}); // });
const { wrapper } = setupMocks({ // const { wrapper } = setupMocks({
querySelectorFunction: function (query) { // querySelectorFunction: function (query) {
if (query == ".pac-container .pac-item > .pac-item-query") { // if (query == ".pac-container .pac-item > .pac-item-query") {
let element = document.createElement("div"); // let element = document.createElement("div");
element.textContent = "123 Test Street"; // element.textContent = "123 Test Street";
return element; // return element;
} else if (query == ".pac-container .pac-item > span:nth-child(3)") { // } else if (query == ".pac-container .pac-item > span:nth-child(3)") {
let element = document.createElement("div"); // let element = document.createElement("div");
element.textContent = "Columbus, OH 43230"; // element.textContent = "Columbus, OH 43230";
return element; // return element;
} // }
}, // },
}); // });
let noMatchAlert = wrapper.findComponent({ ref: "alertNoMatchWarning" }); // let noMatchAlert = wrapper.findComponent({ ref: "alertNoMatchWarning" });
let verificationAlert = wrapper.findComponent({ ref: "alertVerificationWarning" }); // let verificationAlert = wrapper.findComponent({ ref: "alertVerificationWarning" });
expect(noMatchAlert.exists()).toBeFalsy(); // expect(noMatchAlert.exists()).toBeFalsy();
expect(verificationAlert.exists()).toBeFalsy(); // expect(verificationAlert.exists()).toBeFalsy();
await wrapper.vm.$nextTick(); // await wrapper.vm.$nextTick();
// Act // // Act
changeEventCallbackFunction(); // changeEventCallbackFunction();
await wrapper.vm.$nextTick(); // await wrapper.vm.$nextTick();
// Assert // // Assert
verificationAlert = wrapper.findComponent({ ref: "alertVerificationWarning" }); // verificationAlert = wrapper.findComponent({ ref: "alertVerificationWarning" });
expect(wrapper.vm.displayVerificationWarning).toBeTruthy(); // expect(wrapper.vm.displayVerificationWarning).toBeTruthy();
expect(verificationAlert.exists()).toBeTruthy(); // expect(verificationAlert.exists()).toBeTruthy();
expect(verificationAlert.isVisible()).toBeTruthy(); // expect(verificationAlert.isVisible()).toBeTruthy();
noMatchAlert = wrapper.findComponent({ ref: "alertNoMatchWarning" }); // noMatchAlert = wrapper.findComponent({ ref: "alertNoMatchWarning" });
expect(wrapper.vm.displayNoMatchWarning).toBeFalsy(); // expect(wrapper.vm.displayNoMatchWarning).toBeFalsy();
expect(noMatchAlert.exists()).toBeFalsy(); // expect(noMatchAlert.exists()).toBeFalsy();
}); // });
describe("noMatch alert is cleared on address change", () => { describe("noMatch alert is cleared on address change", () => {
test("user sees noMatch warning and modifies street address => noMatch warning is removed", async () => { test("user sees noMatch warning and modifies street address => noMatch warning is removed", async () => {
@ -578,6 +587,7 @@ function setupMocks({
isShallowMount = true, isShallowMount = true,
querySelectorFunction, querySelectorFunction,
geocoderResult = ["1234 Test Street"], geocoderResult = ["1234 Test Street"],
matchFound = false,
}) { }) {
store.commit(storeMutations.RESET_STATE); store.commit(storeMutations.RESET_STATE);
@ -590,6 +600,12 @@ function setupMocks({
loadScript: jest.fn().mockResolvedValue(), loadScript: jest.fn().mockResolvedValue(),
}); });
if (props) resultingMountOptions.propsData = props;
const wrapper = isShallowMount
? shallowMount(addressQuestions, resultingMountOptions)
: mount(addressQuestions, resultingMountOptions);
window.google = { window.google = {
maps: { maps: {
event: { event: {
@ -604,13 +620,15 @@ function setupMocks({
}), }),
removeListener: jest.fn(), removeListener: jest.fn(),
clearInstanceListeners: jest.fn(), clearInstanceListeners: jest.fn(),
trigger: jest.fn().mockImplementation((element, eventName) => {
wrapper.vm.matchFound = matchFound;
}),
}, },
places: { places: {
Autocomplete: jest.fn().mockImplementation((el) => el), Autocomplete: jest.fn().mockImplementation((el) => el),
}, },
Geocoder: class Geocoder { Geocoder: class Geocoder {
// constructor(); // constructor();
geocode(request, callback) { geocode(request, callback) {
callback([geocoderResult], true); callback([geocoderResult], true);
} }
@ -621,12 +639,6 @@ function setupMocks({
}, },
}; };
if (props) resultingMountOptions.propsData = props;
const wrapper = isShallowMount
? shallowMount(addressQuestions, resultingMountOptions)
: mount(addressQuestions, resultingMountOptions);
document.querySelector = jest.fn().mockImplementation((query) => { document.querySelector = jest.fn().mockImplementation((query) => {
let result = null; let result = null;
if (query == ".pac-container") result = document.createElement("div"); if (query == ".pac-container") result = document.createElement("div");

View file

@ -266,31 +266,7 @@ export default {
// When either of the two enter keys or the tab key are pressed // When either of the two enter keys or the tab key are pressed
if (e.code === "Enter" || e.code === "NumpadEnter" || e.code === "Tab") { if (e.code === "Enter" || e.code === "NumpadEnter" || e.code === "Tab") {
// Grab the selected item window.google.maps.event.trigger(this.autocomplete, "place_changed");
const selectedItem = document.querySelector(".pac-item-selected");
if (selectedItem == null) {
// If there is no selected item, fill-in the address using first item from the list.
this.fillInAddressUsingFirstItem();
}
} else {
return;
}
});
this.addressField1.addEventListener("change", () => {
// If a match has been previously attempted then do nothing
if (this.matchFound !== null) {
return;
}
// Get the address that the user clicked on (if any)
const clickedAddress = document.querySelector(".pac-container .pac-item:hover");
// If the Street Address field changed without clicking (i.e. by pressing Tab, or clicking outside the field)
if (clickedAddress === null) {
// Fill-in the address using first item in the list.
this.fillInAddressUsingFirstItem();
} }
}); });
}, },
@ -309,6 +285,12 @@ export default {
place = this.autocomplete.getPlace(); place = this.autocomplete.getPlace();
} }
const selectedItem = document.querySelector(".pac-item-selected");
if (!place && !selectedItem) {
this.fillInAddressUsingFirstItem();
return;
}
if (place && place.address_components) { if (place && place.address_components) {
this.matchFound = true; this.matchFound = true;
const self = this; const self = this;
@ -352,48 +334,18 @@ export default {
(state ?? "") !== "" && (state ?? "") !== "" &&
(zipCode ?? "") !== ""; (zipCode ?? "") !== "";
self.addressModel.streetAddress = `${streetNumber} ${route}`; self.addressModel.streetAddress =
streetNumber && route ? `${streetNumber} ${route}` : `${route}`;
self.addressModel.city = city; self.addressModel.city = city;
self.addressModel.state = state; self.addressModel.state = state;
self.addressModel.zipCode = zipCode; self.addressModel.zipCode = zipCode;
if (!this.displayVerificationWarning) { if (!this.displayVerificationWarning) {
this.displayVerificationWarning = !isAddressComplete || place.partial_match; this.displayVerificationWarning = place.partial_match || !isAddressComplete;
} }
// for (const component of place.address_components) {
// const componentType = component.types[0];
// switch (componentType) {
// // case "street_number": {
// // self.addressModel.streetAddress = component.long_name;
// // break;
// // }
// // case "route": {
// // self.addressModel.streetAddress += " " + component.short_name;
// // break;
// // }
// // case "locality": {
// // self.addressModel.city = component.long_name;
// // break;
// // }
// // case "administrative_area_level_1": {
// // self.addressModel.state = component.short_name;
// // break;
// // }
// // case "postal_code": {
// // self.addressModel.zipCode = component.long_name;
// // break;
// // }
// }
// }
// After filling in the address fields, disable the address autocomplete // After filling in the address fields, disable the address autocomplete
this.unloadAutocomplete(); this.unloadAutocomplete();
// Restore focus to the first address field
//this.addressField1.focus();
}); });
} }
}, },