Skip to content

Commit c2732eb

Browse files
authored
Creating test suite for js/themebox.js (#4377)
1 parent dbb32fd commit c2732eb

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

js/__tests__/themebox.test.js

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
global._ = jest.fn((str) => str);
2+
const ThemeBox = require("../themebox");
3+
4+
describe("ThemeBox", () => {
5+
let mockActivity;
6+
let themeBox;
7+
8+
beforeEach(() => {
9+
mockActivity = {
10+
storage: {
11+
themePreference: "light"
12+
},
13+
textMsg: jest.fn()
14+
};
15+
16+
jest.spyOn(global.Storage.prototype, "getItem").mockImplementation((key) => {
17+
return key === "themePreference" ? "light" : null;
18+
});
19+
jest.spyOn(global.Storage.prototype, "setItem").mockImplementation(() => {});
20+
21+
Object.defineProperty(window, "location", {
22+
value: { reload: jest.fn() },
23+
writable: true,
24+
});
25+
26+
themeBox = new ThemeBox(mockActivity);
27+
});
28+
29+
afterEach(() => {
30+
jest.restoreAllMocks();
31+
});
32+
33+
test("constructor initializes theme from activity storage", () => {
34+
expect(themeBox._theme).toBe("light");
35+
});
36+
37+
test("light_onclick() sets theme to light and updates preference", () => {
38+
themeBox.light_onclick();
39+
expect(themeBox._theme).toBe("light");
40+
expect(localStorage.getItem).toHaveBeenCalledWith("themePreference");
41+
expect(mockActivity.textMsg).toHaveBeenCalledWith("Music Blocks is already set to this theme.");
42+
});
43+
44+
test("dark_onclick() sets theme to dark and updates preference", () => {
45+
themeBox.dark_onclick();
46+
expect(themeBox._theme).toBe("dark");
47+
expect(mockActivity.storage.themePreference).toBe("dark");
48+
expect(window.location.reload).toHaveBeenCalled();
49+
});
50+
51+
test("setPreference() updates theme and reloads if different", () => {
52+
localStorage.getItem.mockReturnValue("dark"); // Correctly mocked now
53+
themeBox.light_onclick();
54+
expect(mockActivity.storage.themePreference).toBe("light");
55+
expect(window.location.reload).toHaveBeenCalled();
56+
});
57+
58+
test("setPreference() does not reload if theme is unchanged", () => {
59+
themeBox.light_onclick();
60+
expect(window.location.reload).not.toHaveBeenCalled();
61+
});
62+
});

0 commit comments

Comments
 (0)