Setting Up and Tearing Down Jasmine Tests
Learn how to set up Jasmine tests and clean up after they run.
The beforeEach
and afterEach
functions
In the example below, we have two tests. In each case, we create a book
object and then call a function on it. On line 1, the getShortSummary
function uses string interpolation to combine the title
and year
values. On line 6, the getLongSummary
function uses string interpolation to combine the title
, author
, and year
values.
We use the beforeEach
function on line 14. The beforeEach
function takes an anonymous function as its argument and runs it before each test. In the example, we use the beforeEach
function to reset the value of the book
object. This makes our test code cleaner and also protects us from accidentally changing the value of the book
object in one of the tests.
Jasmine also gives us an afterEach
method, which lets us run a function after each test finishes. We can use this afterEach
method to clean up our variables after the tests run. We call the afterEach
function on line 32.
Get hands-on with 1400+ tech skills courses.