DRY’ing up setup and teardown of your Protractor Jasmine Spec

Pattern for Creating General Pre- and Post-Processing Methods in Protractor

Please refer to the official documentation of Jasmine here

Guest Post by Jeff Gosnell

A question was recently asked on the Gitter Protractor site
wondering what is the best way to reduce code copy-paste when needing to do the same beforeEach, beforeAll, afterEach, and/or afterAll code in multiple Spec.js files.

This post will cover Protractor and JavaScript, but if you need it for C#, Java, or some other structured language, you would create a static class or a class with static functions.

In most cases, if you want to reduce copy and pasting (DRY) code, put that code in a method (function) and ensure it can be called from whatever class or file it is needed in.

In JavaScript, and in particular Node.js, this is the pattern I would use. (The method names and file names are generic. Modify them to your desires. This is just the pattern.)

Any other spec.js files that you create where you need the ProcessingMethods methods, make sure you import that class using require. You’ll want to make sure that the methods are built in a generic way such that you can use it with many of your spec files.

For example, in the beforeAll, you may want to pass in the server URL that will be under test. And the beforeEach will need to load a specific page.

So, you might have a login-spec.js file where you are testing your login page.

The beforeEach method might be:

Another suggestion I might have is to pass in the URL while creating the ProcessingMethods object. Therefore, it would look something like this:

Then in the spec.js file, you would:

Author: Jeff Gosnell

2 thoughts on “DRY’ing up setup and teardown of your Protractor Jasmine Spec

Leave a Comment

Website Protected by Spam Master