Skip to content

Commit

Permalink
fix: [#1689] HTMLElement.dataset should return undefined for properti…
Browse files Browse the repository at this point in the history
…es not found (#1738)
  • Loading branch information
karpiuMG authored Feb 24, 2025
1 parent 6c5e0f9 commit 33f1beb
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 3 deletions.
4 changes: 2 additions & 2 deletions packages/happy-dom/src/dom/DOMStringMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,11 @@ export default class DOMStringMap {
// Documentation for Proxy:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
return new Proxy(this, {
get(_target, property: string): string {
get(_target, property: string): string | void {
const attribute = element.getAttribute(
'data-' + DOMStringMapUtility.camelCaseToKebab(property)
);
if (attribute) {
if (attribute !== null) {
return attribute;
}
},
Expand Down
2 changes: 1 addition & 1 deletion packages/happy-dom/src/nodes/element/Element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ export default class Element
*
* @param name Name.
*/
public getAttribute(name: string): string {
public getAttribute(name: string): string | null {
const attribute = this[PropertySymbol.attributes].getNamedItem(name);
if (attribute) {
return attribute[PropertySymbol.value];
Expand Down
7 changes: 7 additions & 0 deletions packages/happy-dom/test/nodes/element/Element.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1774,6 +1774,13 @@ describe('Element', () => {
});
});

describe('getAttribute()', () => {
it('Returns null when cannot find attribute.', () => {
element.setAttribute('key2', '');
expect(element.getAttribute('random')).toEqual(null);
});
});

describe('getAttributeNames()', () => {
it('Returns attribute names.', () => {
element.setAttributeNS(NAMESPACE_URI, 'global:local1', 'value1');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -334,6 +334,15 @@ describe('HTMLElement', () => {
const button = <HTMLElement>main.querySelector('button');
expect(button.closest('[data-test]')).toBe(div);
});

it('Handles empty string values correctly', () => {
element.setAttribute('data-test-empty', '');
const dataset = element.dataset;
expect(dataset.testEmpty).toBe('');
expect(dataset.nonExistentKey).toBeUndefined();
dataset.testEmptyAlso = '';
expect(dataset.testEmptyAlso).toBe('');
});
});

describe('get dir()', () => {
Expand Down

0 comments on commit 33f1beb

Please sign in to comment.