Skip to content

Commit

Permalink
SWED-2505 Fixed issue where dropdown could not be initialized with ID
Browse files Browse the repository at this point in the history
  • Loading branch information
Ludvik Lund committed Aug 6, 2024
1 parent f2e1919 commit 9b19682
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 6 deletions.
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

0 comments on commit 9b19682

Please sign in to comment.