Posted 12 days ago. Visible to the public. Repeats.

Jasmine: Cleaning up the DOM after each test

Jasmine Archive 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:

Copy
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:

Copy
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:

Copy
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> ... }) })

Your development team has a full backlog of feature requests, chores and refactoring coupled with deadlines? We are familiar with that. With our "DevOps as a Service" offering, we support developer teams with infrastructure and operations expertise.

Owner of this card:

Avatar
Henning Koch
Last edit:
8 days ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Henning Koch to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more