4

In this example, why does the variable foo not raise a ReferenceError? There is no variable declaration, but it's clearly in scope after the DOM is rendered. What's the relationship between the DOM node id and the javascript namespace? I'm running this with jest.

import React from 'react';
import { render } from '@testing-library/react'

test('renders a div', () => {
  const { utils } = render(<div id="foo"/>)
  expect(foo).toBe(true)
})

Jest reports:

Expected: true
Received: <div id="foo" />

I really wish the test would crash instead, because in my real example I accidentally passed an undefined variable to expect(), which just happened to share the name of a rendered DOM node's id.

davemfish
  • 172
  • 1
  • 9
  • 3
    Browsers do that for stupid legacy reasons. – Pointy Apr 14 '20 at 21:06
  • 1
    @Pointy can you provide a source that documents this behavior? – Robert Stiffler Apr 14 '20 at 21:08
  • `document.write('
    '); console.log(window.foo)`
    – Lawrence Cherone Apr 14 '20 at 21:09
  • Oh very interesting. I should have gone ever further with minimizing this example. Any reference material about this behavior is appreciated. – davemfish Apr 14 '20 at 21:15
  • https://stackoverflow.com/a/3434388/220272 – a--m Apr 14 '20 at 21:18
  • 1
    @RobertStiffler well probably, but I've been living with it for the better part of 20 years. IE used to do that forever, and Firefox didn't, so there were endless bugs because of that. It's similar to the issue of the global `event` reference vs. the parameter passed to event handlers. – Pointy Apr 14 '20 at 21:29
  • 1
    @Pointy Based on the accepted answer, it appears this was originally unstandardized behavior of IE, but has now been "standardized by HTML5, whose approach is to document and standardize every terrible practice inflicted on us by browser authors, making them part of the web forever". :( – Robert Stiffler Apr 14 '20 at 21:36

1 Answers1

3

Elements with ids become global variables

Not the same question, but the answer to your question is another SO question:

Do DOM tree elements with ids become global variables?

a--m
  • 4,716
  • 1
  • 39
  • 59