Gianluca Ghettini
Gianluca Ghettini

Reputation: 11628

How to organize unit tests and e2e tests in AngularJS?

I need to organize unit tests and end to end tests for my JavaScript Single Page Application. I'm using AngularJS Protractor/Cucumber for e2e testing and Chai for unit tests.

I have e2e and unit tests in two different folders (unit and e2e folder) and I'm currently not taking advantage of the page object design patterm. The files are unstructured and don't share a lot of code, so I'm repeating myself many times.

I recognize this approach doesn't scale up

Is there a best practice to reorganize the tests in such a way I write the least amount of code, keeping the test code DRY?

Upvotes: 5

Views: 1615

Answers (1)

alecxe
alecxe

Reputation: 473803

First of all, you should definitely switch to using the Page Object pattern and keep your page objects under a separate directory - I think it's recommended to call the directory po.

Here is a sample for you, the project structure we currently have:

$ cd e2e
$ tree -L 1
.
├── config
├── db
├── helpers
├── mocks
├── po
└── specs

config is special directory where we keep our protractor configs - there could be multiple configs - for instance, for local testing and for testing on, say, BrowserStack.

helpers is, basically, our "libs"/"utils" directory. We keep custom jasmine matchers, additional "helper" modules with helper functions. Also, we have localStorage and sessionStorage modules that are convenient wrappers around window.localStorage and window.sessionStorage objects.

mocks is a directory where we keep protractor-http-mock mocks.

po is a directory where Page Objects are defined. Each Page Object in a separate file.

specs is where all of our specs live - they are organized into subdirectories logically.


Some of the helpers libraries are made globally available via global, example:

onPrepare: function () {
     global.helpers = require("../helpers/helpers.js");
     // ...
},

Also, to make the helpers and po import more convenient and avoid traversing the directories up in the tree and to better handle the nestedness, we've switched to using requirePO and requireHelper helper function suggested by @Michael Radionov, see:

I also really like the idea, proposed by @finspin, to make a node package out of each Page Object.

Upvotes: 7

Related Questions