You are on page 1of 2

BeforeEach, AfterEach, BeforeAll, and AfterAll

------------------------------The BeforeEach and AfterEach commands allow you to define setup and teardown tas
ks that are
performed at the beginning and end of every It block. This can eliminate duplica
tion of code
in test scripts, ensure that each test is performed on a pristine state regardle
ss of their
order, and perform any necessary cleanup tasks after each test.
BeforeEach and AfterEach blocks may be defined inside of any Describe or Context
. If they
are present in both a Context and its parent Describe, BeforeEach blocks in the
Describe scope
are executed first, followed by BeforeEach blocks in the Context scope. AfterEac
h blocks are
the reverse of this, with the Context AfterEach blocks executing before Describ
e.
The script blocks assigned to BeforeEach and AfterEach are dot-sourced in the Co
ntext or Describe
which contains the current It statement, so you don't have to worry about the sc
ope of variable
assignments. Any variables that are assigned values within a BeforeEach block ca
n be used inside
the body of the It block.
BeforeAll and AfterAll are used the same way as BeforeEach and AfterEach, except
that they are
executed at the beginning and end of their containing Describe or Context block.
This is
essentially syntactic sugar for the following arrangement of code:
Describe 'Something' {
try
{
<BeforeAll Code Here>
<Describe Body>
}
finally
{
<AfterAll Code Here>
}
}
Note about syntax and placement
------------------------------Unlike most of the commands in a Pester script, BeforeEach, AfterEach, BeforeAll
and AfterAll blocks
apply to the entire Describe or Context scope in which they are defined, regardl
ess of the order of
commands inside the Describe or Context. In other words, even if an It block app
ears before BeforeEach
or AfterEach in the tests file, the BeforeEach and AfterEach will still be execu
ted. Likewise, BeforeAll
code will be executed at the beginning of a Context or Describe block regardless
of where it is found,

and AfterAll code will execute at the end of the Context or Describe.
Examples
------------------------------Describe 'Testing BeforeEach and AfterEach' {
$afterEachVariable = 'AfterEach has not been executed yet'
It 'Demonstrates that BeforeEach
$beforeEachVariable | Should
$afterEachVariable | Should
$beforeAllVariable | Should
}

may be defined after the It command' {


Be 'Set in a describe-scoped BeforeEach'
Be 'AfterEach has not been executed yet'
Be 'BeforeAll has been executed'

It 'Demonstrates that AfterEach has executed after the end of the first test
' {
$afterEachVariable | Should Be 'AfterEach has been executed'
}
BeforeEach {
$beforeEachVariable = 'Set in a describe-scoped BeforeEach'
}
AfterEach {
$afterEachVariable = 'AfterEach has been executed'
}
BeforeAll {
$beforeAllVariable = 'BeforeAll has been executed'
}
}

You might also like