Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SWED-2505 Fixed issue where dropdown could not be initialized with ID #996

Merged
merged 1 commit into from
Aug 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 8 additions & 4 deletions src/scripts/main/dropdown/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,21 @@ const init = (id) => {
let dropdownMenu;

if (id) {
dropdownContainers = document?.getElementById(id);
/* Find the dropdown container by id, and wrap it in a NodeList like structure to
avoid friction in the rest of the code */
const element = document.getElementById(id);
dropdownContainers = element ? [element] : [];

if (!dropdownContainers) {
if (!dropdownContainers.length) {
console.error(
`No dropdown found corresponding with the id provided in dropdown.init() passing this id value: "${id}"`,
);

return null;
}
dropdownToggles = dropdownContainers.querySelector(SELECTORS.TOGGLE);
dropdownMenu = dropdownContainers.querySelector(SELECTORS.DROPDOWNMENU);

dropdownToggles = element.querySelectorAll(SELECTORS.TOGGLE);
dropdownMenu = element.querySelectorAll(SELECTORS.DROPDOWNMENU);
} else {
dropdownContainers = document.querySelectorAll(SELECTORS.DROPDOWNLIST);
dropdownToggles = document.querySelectorAll(
Expand Down
21 changes: 19 additions & 2 deletions src/scripts/main/dropdown/index.test.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React from "react";
import { render, screen } from "@testing-library/react";
import { render } from "@testing-library/react";
import "@testing-library/jest-dom";
import userEvent from "@testing-library/user-event";

import dropdown from "./index";

Expand Down Expand Up @@ -50,6 +49,24 @@ describe("Scripts: Dropdown", () => {
expect(dropdown.init()).toBeNull();
expect(console.warn).toHaveBeenCalled();
});

it("initializes with ID", () => {
render(<Dropdown id="foo" />);

console.warn = jest.fn();

expect(dropdown.init("foo")).not.toBeNull();
expect(console.warn).not.toHaveBeenCalled();
});

it("init returns null if no dropdown with ID is found and prints a warning message", () => {
render(<Dropdown id="foo" />);

console.error = jest.fn();

expect(dropdown.init("bar")).toBeNull();
expect(console.error).toHaveBeenCalled();
});
});

it("button click gives dropdown-div class of active", () => {
Expand Down
Loading