Read more

Jasmine: Cleaning up the DOM after each test

Henning Koch
November 17, 2022Software engineer at makandra GmbH

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.

Illustration online protection

Rails professionals since 2007

Our laser focus on a single technology has made us a leader in this space. Need help?

  • We build a solid first version of your product
  • We train your development team
  • We rescue your project in trouble
Read more Show archive.org snapshot

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>
    
    ...
  })
})
Posted by Henning Koch to makandra dev (2022-11-17 08:41)