Skip to content

Commit 83c3854

Browse files
committed
test(getStyle): add tests to ensure getStyle never returns undefined for elements and pseudo-elements
1 parent 1e5c978 commit 83c3854

2 files changed

Lines changed: 34 additions & 4 deletions

File tree

__tests__/utils.css.test.js

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,22 @@ describe('getStyle', () => {
99
expect(style).toBeInstanceOf(CSSStyleDeclaration)
1010
document.body.removeChild(el)
1111
})
12+
13+
it('never returns undefined for elements', () => {
14+
const el = document.createElement('div')
15+
document.body.appendChild(el)
16+
const style = getStyle(el)
17+
expect(style).not.toBeUndefined()
18+
document.body.removeChild(el)
19+
})
20+
21+
it('never returns undefined for pseudos', () => {
22+
const el = document.createElement('div')
23+
document.body.appendChild(el)
24+
const pseudoStyle = getStyle(el, '::before')
25+
expect(pseudoStyle).not.toBeUndefined()
26+
document.body.removeChild(el)
27+
})
1228
})
1329

1430
describe('parseContent', () => {

src/utils/css.js

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -270,20 +270,34 @@ export function getStyle(el, pseudo = null) {
270270
const win = typeof window !== 'undefined' ? window : null
271271
return win ? win.getComputedStyle(el, pseudo) : null
272272
}
273-
274273
let map = cache.computedStyle.get(el)
275274
if (!map) {
276275
map = new Map()
277276
cache.computedStyle.set(el, map)
278277
}
279278

280-
if (!map.has(pseudo)) {
279+
let style = map.get(pseudo)
280+
281+
if (!style) {
281282
const win = getWindowForElement(el)
282283
const st = win ? win.getComputedStyle(el, pseudo) : null
283-
if (st) map.set(pseudo, st)
284+
if (st) {
285+
map.set(pseudo, st)
286+
style = st
287+
} else if (typeof window !== 'undefined' && typeof window.getComputedStyle === 'function') {
288+
try {
289+
const fallback = window.getComputedStyle(el, pseudo)
290+
if (fallback) {
291+
style = fallback
292+
map.set(pseudo, fallback)
293+
}
294+
} catch {
295+
// ignore and leave style as null
296+
}
297+
}
284298
}
285299

286-
return map.get(pseudo)
300+
return style
287301
}
288302

289303
/**

0 commit comments

Comments
 (0)