I\'m using the Jasmine BDD Javascript library and really enjoying it. I have test code that I\'d like to reuse (for example, testing multiple implementations of a base clas
This is the approach I have taken, inspired by this article:
https://gist.github.com/traviskaufman/11131303
which is based on Jasmine own documentation:
http://jasmine.github.io/2.0/introduction.html#section-The_%3Ccode%3Ethis%3C/code%3E_keyword
By setting shared dependencies as properties of beforeEach
function prototype, you can extend beforeEach
to make this dependencies available via this
.
Example:
describe('A suite', function() {
// Shared setup for nested suites
beforeEach(function() {
// For the sake of simplicity this is just a string
// but it could be anything
this.sharedDependency = 'Some dependency';
});
describe('A nested suite', function() {
var dependency;
beforeEach(function() {
// This works!
dependency = this.sharedDependency;
});
it('Dependency should be defined', function() {
expect(dependency).toBeDefined();
});
});
describe('Check if string split method works', function() {
var splitToArray;
beforeEach(function() {
splitToArray = this.sharedDependency.split();
});
it('Some other test', function() { ... });
});
});
I know my example is kind of useless but it should serve its purpose as code example.
Of course this is just one of the many things you could do to achieve what you say, I'm sure that more complex design patterns may be applied on top or aside to this one.
Hope it helps!
Here is an article by a guy at Pivotal Labs that goes into detail about how to wrap a describe call:
DRYing up Jasmine Specs with Shared Behavior
Snippet from the article that shows part of the wrapper function:
function sharedBehaviorForGameOf(context) {
describe("(shared)", function() {
var ball, game;
beforeEach(function() {
ball = context.ball;
game = context.game;
});
});
}