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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)