Jasmine: Cleaning up the DOM after each test

Jasmine Show archive.org snapshot specs that work with DOM elements often leave elements in the DOM after they're done. This will leak test-local DOM state to subsequent tests.

For example, this test creates a <spoiler-text> element, runs some expectations, and then forgets to remove it from the DOM:

describe('<spoiler-text>', function() {
  it ('hides the secret until clicked', function() {
    let element = document.createElement('spoiler-text')
    element.secret = 'The butler did it'
    document.body.appendChild(element)
    
    expect(element).toHaveText('Click to show spoiler')
    
    element.click()
    
    expect(element).toHaveText('The butler did it')
  })
})

To address this I like to configure a global container for test elements, which is cleared automatically after each test. By including the following helper hooks your tests can call jasmine.fixtures to access a <div> container that is emptied once the test concludes:

beforeAll(function() {
  jasmine.fixtures = document.createElement('div')
  document.body.appendChild(jasmine.fixtures)
})

afterEach(function() {
  jasmine.fixtures.innerHTML = ''
})

In your tests, append your test elements to jasmine.fixtures instead of document.body:

describe('<spoiler-text>', function() {
  it ('hides the secret until clicked', function() {
    let element = document.createElement('spoiler-text')
    element.secret = 'The butler did it'
    jasmine.fixtures.appendChild(element) // <== not appending to <body>
    
    ...
  })
})
Henning Koch Over 1 year ago