Skip to content

Commit 33f1beb

Browse files
authored
fix: [#1689] HTMLElement.dataset should return undefined for properties not found (#1738)
1 parent 6c5e0f9 commit 33f1beb

File tree

4 files changed

+19
-3
lines changed

4 files changed

+19
-3
lines changed

packages/happy-dom/src/dom/DOMStringMap.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ export default class DOMStringMap {
2525
// Documentation for Proxy:
2626
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
2727
return new Proxy(this, {
28-
get(_target, property: string): string {
28+
get(_target, property: string): string | void {
2929
const attribute = element.getAttribute(
3030
'data-' + DOMStringMapUtility.camelCaseToKebab(property)
3131
);
32-
if (attribute) {
32+
if (attribute !== null) {
3333
return attribute;
3434
}
3535
},

packages/happy-dom/src/nodes/element/Element.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -741,7 +741,7 @@ export default class Element
741741
*
742742
* @param name Name.
743743
*/
744-
public getAttribute(name: string): string {
744+
public getAttribute(name: string): string | null {
745745
const attribute = this[PropertySymbol.attributes].getNamedItem(name);
746746
if (attribute) {
747747
return attribute[PropertySymbol.value];

packages/happy-dom/test/nodes/element/Element.test.ts

+7
Original file line numberDiff line numberDiff line change
@@ -1774,6 +1774,13 @@ describe('Element', () => {
17741774
});
17751775
});
17761776

1777+
describe('getAttribute()', () => {
1778+
it('Returns null when cannot find attribute.', () => {
1779+
element.setAttribute('key2', '');
1780+
expect(element.getAttribute('random')).toEqual(null);
1781+
});
1782+
});
1783+
17771784
describe('getAttributeNames()', () => {
17781785
it('Returns attribute names.', () => {
17791786
element.setAttributeNS(NAMESPACE_URI, 'global:local1', 'value1');

packages/happy-dom/test/nodes/html-element/HTMLElement.test.ts

+9
Original file line numberDiff line numberDiff line change
@@ -334,6 +334,15 @@ describe('HTMLElement', () => {
334334
const button = <HTMLElement>main.querySelector('button');
335335
expect(button.closest('[data-test]')).toBe(div);
336336
});
337+
338+
it('Handles empty string values correctly', () => {
339+
element.setAttribute('data-test-empty', '');
340+
const dataset = element.dataset;
341+
expect(dataset.testEmpty).toBe('');
342+
expect(dataset.nonExistentKey).toBeUndefined();
343+
dataset.testEmptyAlso = '';
344+
expect(dataset.testEmptyAlso).toBe('');
345+
});
337346
});
338347

339348
describe('get dir()', () => {

0 commit comments

Comments
 (0)