Skip to content

Instantly share code, notes, and snippets.

@cben
Last active October 2, 2015 06:13
Show Gist options
  • Select an option

  • Save cben/43fcbbae95019aa73ecd to your computer and use it in GitHub Desktop.

Select an option

Save cben/43fcbbae95019aa73ecd to your computer and use it in GitHub Desktop.
Jasmine: Using in a test a value set in beforeAll/Each

Using Jasmine 2, I want to:

  1. compute a value in a beforeAll/beforeEach block
  2. access it in the it / nested describe block

so far easy: set a var and use it [OUT below]. It will have right values by the time it runs.

  1. extract test cases / nested suite into a function.

That's harder, especially with nested suites - nested describe body is executed immediately, before any beforeEach/All blocks. Trying to passing the outer variable would pass the initial undefined/null [IN1 below]. => Passing a closure to get current value of the variable works if you only call it from it blocks [IN2 below].

Using Mocha, the exact same thing happens - just replace beforeAll->`before`, afterAll->`after`.

inner1 = (x) ->
y = null
describe 'IN1', ->
console.log('IN1: x =', x, ', y =', y)
beforeAll (done) ->
y = 'IN1 before'
console.log('IN1 before: x =', x, ', y =', y)
done()
it 'SHOULD', (done) ->
console.log('IN1 SHOULD: x =', x, ', y =', y)
done()
afterAll (done) ->
console.log('IN1 after: x =', x, ', y =', y)
done()
inner2 = (getX) ->
y = null
describe 'IN2', ->
console.log('IN2: x =', getX(), ', y =', y)
beforeAll (done) ->
y = 'IN2 before'
console.log('IN2 before: x =', getX(), ', y =', y)
done()
it 'SHOULD', (done) ->
console.log('IN2 SHOULD: x =', getX(), ', y =', y)
done()
afterAll (done) ->
console.log('IN2 after: x =', getX(), ', y =', y)
done()
describe 'OUT', ->
x = null
beforeAll (done) ->
x = 'OUT before'
console.log('OUT before: x =', x)
done()
inner1(x)
inner2(-> x)
afterAll (done) ->
console.log('OUT after: x =', x)
done()
$ jasmine
IN1: x = null , y = null
IN2: x = null , y = null
Started
OUT before: x = OUT before
IN1 before: x = null , y = IN1 before
IN1 SHOULD: x = null , y = IN1 before
.IN1 after: x = null , y = IN1 before
IN2 before: x = OUT before , y = IN2 before
IN2 SHOULD: x = OUT before , y = IN2 before
.IN2 after: x = OUT before , y = IN2 before
OUT after: x = OUT before
2 specs, 0 failures
$ mocha
IN1: x = null , y = null
IN2: x = null , y = null
OUT
OUT before: x = OUT before
IN1
IN1 before: x = null , y = IN1 before
IN1 SHOULD: x = null , y = IN1 before
✓ SHOULD
IN1 after: x = null , y = IN1 before
IN2
IN2 before: x = OUT before , y = IN2 before
IN2 SHOULD: x = OUT before , y = IN2 before
✓ SHOULD
IN2 after: x = OUT before , y = IN2 before
OUT after: x = OUT before
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment