What's a good way to reuse test code using Jasmine?

glenn picture glenn · Feb 21, 2011 · Viewed 17.1k times · Source

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 class or running the same tests in a slightly different context) and I'm not sure how to do it using Jasmine. I know that I could move code out of the jasmine functions and into reusable classes but I like the way the code reads interspersed with the Jasmine functions (describe, it) and I don't want to separate the specs from the test code unless I have to. Has anyone out there using Jasmine come across this issue and how have you handled it?

Answer

starmer picture starmer · Jun 22, 2011

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;
    });
  });
}