Skip to content

Instantly share code, notes, and snippets.

@tkareine
Created December 15, 2011 13:18
Show Gist options
  • Save tkareine/1481060 to your computer and use it in GitHub Desktop.
Save tkareine/1481060 to your computer and use it in GitHub Desktop.
beforeAll decorator for Jasmine
function withBeforeAll(tests) {
var beforeAllCalled = false
var helpers = {
beforeAll: function (fun) {
beforeEach(function () {
if (beforeAllCalled) return
fun()
runs(function () { beforeAllCalled = true } )
})
}
}
return function () { tests(helpers) } // when Jasmine calls tests, they execute with our helpers
}
describe('when using setup-like behavior in a suite', withBeforeAll(function (b) {
var outerMonitor = []
b.beforeAll(function () { outerMonitor.push(1) })
it ('calls beforeAll before this test', function () {
expect(outerMonitor).toExist()
})
it ('calls beforeAll only once (this must not be the first test in its suite)', function () {
expect(outerMonitor).toEqual([1])
})
describe('when nested suite', withBeforeAll(function (newB) {
var innerMonitor = []
newB.beforeAll(function () { innerMonitor.push(2) })
it ('calls beforeAll of the outer suite only once', function () {
expect(outerMonitor).toEqual([1])
})
it ('calls beforeAll of the current suite only once', function () {
expect(innerMonitor).toEqual([2])
})
}))
}))
@filipefmelo
Copy link

Hi tkareine, could you explain how to add a decorator do Jasmine, please?

@almirfilho
Copy link

Yeah.. it would be nice =)

@emilwall
Copy link

This example is insufficient to demonstrate the point of a beforeAll hook since the push statements could be placed directly after the variable declarations instead, but maybe motivating beforeAll was not the intention of the example specs.

Note that if a beforeEach statement appears before a beforeAll statement, it will be executed before the beforeAll. A typical scenario where this could happen is when there is a beforeEach at the top of the outer describe. I leave it up to you to decide whether this is a feature or a bug.

I have spent some time trying to implement a similar decorator for afterAll, but I couldn't find a reliable way to count the number of specs that should run before it is executed, and even if I managed to, there would still be concerns about how to get it to run in the correct order compared to other afterAll and afterEach callbacks. Please let me know if there is a solution to this.

I wish pivotal could have merged jasmine/jasmine#56. This will definitely be mentioned when I compare Jasmine with Mocha in my master thesis about JavaScript testing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment