How to organize unit tests and e2e tests in AngularJS?
Asked Answered
E

1

5

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?

Evita answered 16/11, 2015 at 15:37 Comment(0)
A
7

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.

Aerification answered 16/11, 2015 at 22:50 Comment(4)
do you have any example of Page Object?Evita
@GianlucaGhettini yup, we basically follow what is suggested here: github.com/angular/protractor/blob/master/docs/page-objects.md.Aerification
does it make sense to have something like page objects for unit tests as well?Querist
@Querist I don't think so. Page objects help to abstract away the UI, split your application UI into convenient objects to work with in your tests. In unit tests you have a direct access to the source code and there is no UI to build abstractions on top of. Hope that helps. Thanks.Aerification

© 2022 - 2024 — McMap. All rights reserved.